简体   繁体   中英

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:

(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:

<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.

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

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

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:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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