javascript js iframe 关闭按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11775481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:18:06  来源:igfitidea点击:

js iframe close button

javascripthtmliframe

提问by Darren Sweeney

I Have the following which opens an iframe with html page loaded, works great, but how to add a close button to the page/iframe so it simply closes the iframe/page and does not affect the page its opened over:

我有以下内容打开一个加载了 html 页面的 iframe,效果很好,但是如何向页面/iframe 添加关闭按钮,以便它只是关闭 iframe/页面并且不会影响其打开的页面:

(function (d) {
var modal = document.createElement('iframe');
modal.setAttribute('src', 'mypage.html'));
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/testes.css';
document.body.appendChild(c);
}(document));

I tried the following which tried to close it, but, then gives a 404 message inside the iframe:

我尝试了以下尝试关闭它,但是,然后在 iframe 中给出了 404 消息:

<a href="window.parent.document.getElementById('iframe').parentNode.removeChild(window.parent.document.getElementById('iframe'))">Close</a>

I am loading jquery on the page if that helps at all, meaning, if there is a jquery solution.

如果有帮助,我正在页面上加载 jquery,意思是,如果有 jquery 解决方案。

回答by Quentin

Links are supposed to link somewhere and the hrefattribute takes a URI.

链接应该链接到某个地方,并且该href属性采用 URI。

Use a <button type="button">and bind a click handler to it. (You could use an onclickattribute, but that wouldn't be unobtrusive)

使用 a<button type="button">并将点击处理程序绑定到它。(你可以使用一个onclick属性,但这不会不显眼

The unobtrusive approach would be:

不显眼的方法是:

<a href="someUriWithoutAnIframe" target="_parent">foo</a>

And then bind an event handler along the lines of

然后绑定一个事件处理程序

myLink.addEventListener('click', function (e) {
    var d = window.parent.document;
    var frame = d.getElementById('myFrame');
    frame.parentNode.removeChild(frame);
    e.preventDefault();
});

回答by Nicolas Stamm

You could put the link into some kind of container div for your iframe, creating the latter with this structure:

您可以将链接放入 iframe 的某种容器 div 中,使用以下结构创建后者:

<div id="iframe-container">
  <a href='#' onclick='this.parentNode.parentNode.removeChild(this.parentNode)'>Close</a>
  <iframe src="http://some.web/page.html" />
</div>

Works without any framework.

无需任何框架即可工作。