简体   繁体   English

在外部点击时关闭iframe

[英]Close iframe when click outside

How can i close an iframe when I click outside ? 我在外面单击时如何关闭iframe?

This is how I'm creating the iframe on the parent 这就是我在父级上创建iframe的方式

    <script type="text/javascript">

function checkip() {
    var iframe = document.createElement("iframe");     
    iframe.id="capa";
    iframe.name="test1";
 iframe.src = "iframe2.html";
 iframe.width = "200";
 iframe.height = "200";
 iframe.frameBorder = "1";
 iframe.scrolling = "no"; 
 //document.body.replaceChild(iframe, lastElementChild);
 document.body.appendChild(iframe);

}
    </script>

This is how im closing the iframe. 这就是我关闭iframe的方式。

   function _ocultarIframe(){

 // document.getElementById('capa').style.display = 'none';
 var elem = document.getElementById("capa");
   elem.parentNode.removeChild(elem);

  }
    </script>

If you don't want to use jQuery, ignore this answer.But it will be easier if you user jQuery. 如果您不想使用jQuery,请忽略此答案,但是使用jQuery会更容易。

jQuery: jQuery的:

$(document).on("click", function(e) {
    //If you click on document it will close the iframe.
    $("iframe").addClass("hide");
});

$("#capa").on("click", function(e) {
    //But if you click on iframe, the default behaviour of closing of iframe is stopped.
    e.stopPropagation();
});

CSS: CSS:

.hide {
    display:none;
}

Check if your iframe is target to click event using Jquery is() and e.target which is A reference to the object that dispatched the event. 使用Jquery is()和e.target(这是对调度事件的对象的引用)检查iframe是否是单击事件的目标。

$("html").click(function(e) {
var iframe = $('#capa');
if (!iframe.is(e.target))     {
    _ocultarIframe();
    }
  });

You could be doing something like this. 您可能正在做这样的事情。

In sense of "closing" Iframe im not sure if you meant to hide/remove/slide it away, but this would just toggle it's height. 在“关闭” iframe的意义上,我不确定您是否要hide/remove/slide它,但这只会切换其高度。

document.addEventListener('click', function () {
  var iFrame = document.querySelector('#capa')
  iFrame.height = iFrame.height > 0 ? 0 : 200 // conditional height toggle
})

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

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