使用按钮关闭 iframe 模式

Close iframe modal with button

本文关键字:iframe 模式 按钮      更新时间:2023-09-26

我正在使用以下内容从书签加载iframe:

javascript:(function(d){
var%20modal=document.createElement('iframe');
modal.setAttribute('src','http://myurl.com/page.html?url=
'+encodeURIComponent(window.location.href)+'&
page_title='+document.title);
modal.setAttribute('scrolling','no');
modal.className='modal';
document.body.appendChild(modal);
var c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='//myurl.com/css/wl_iframe.css';
document.body.appendChild(c);
}(document));

为了关闭它,我正在尝试:

<button onclick="parent.$.iframe.close();">X Close Window</button>

我也试过:

<button onclick="modal.$.iframe.close();">X Close Window</button>

但他们没有工作,他们什么都不做。

我知道我可以使用:

<a href="underneath url" target="_parent">X Close Window</a>

但这会导致浏览器重新刷新他们正在查看的页面,并且用户必须按两次后退按钮才能到达之前的页面,这并不理想。

有什么想法吗?

你应该在iframe中添加一些名称或ID

javascript:(function(d){
var modal=document.createElement('iframe');
modal.setAttribute('src','http://myurl.com/page.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);
modal.setAttribute('scrolling','no');
modal.setAttribute('name', 'my_modal_window');
modal.className='modal';
document.body.appendChild(modal);
var c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='//myurl.com/css/wl_iframe.css';
document.body.appendChild(c);
}(document));

然后

<a href="#" onclick="var modals = document.getElementsByName('my_modal_window'), i = modals.length; while(i--){ modals[i].parentNode.removeChild(modals[i])}">X close window</a>

编辑 工作解决方案,刚刚在Chrome JS控制台内的堆栈溢出上进行了测试:

(function(d){
var modal=document.createElement('iframe');
modal.setAttribute('src','http://myurl.com/page.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);
modal.setAttribute('scrolling','no');
modal.setAttribute('name', 'my_modal_window');
modal.className='modal';
document.body.appendChild(modal);
var c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='/css/wl_iframe.css';
document.body.appendChild(c);
var a = document.createElement('a');
a.onclick= function(){
   var modals = document.getElementsByName('my_modal_window'),i = modals.length;
   while (i--) {
      modals[i].parentNode.removeChild(modals[i]);
   }
};
a.innerHTML = 'Close Iframes';
document.body.appendChild(a);
}(document))