简体   繁体   English

js iframe关闭按钮

[英]js iframe close button

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解决方案。

Links are supposed to link somewhere and the href attribute takes a URI. 链接应该链接到某个地方,并且href属性采用URI。

Use a <button type="button"> and bind a click handler to it. 使用<button type="button">并将点击处理程序绑定到它。 (You could use an onclick attribute, but that wouldn't be unobtrusive ) (您可以使用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();
});

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. 无需任何框架即可工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM