在外部点击时关闭iframe

时间:2018-09-11 22:15:10

标签: javascript

当我在外部单击时如何关闭iframe?

这就是我在父级上创建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>

这就是关闭iframe的方式。

   function _ocultarIframe(){

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

  }
    </script>

3 个答案:

答案 0 :(得分:0)

如果您不想使用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:

.hide {
    display:none;
}

答案 1 :(得分:0)

使用Jquery is()和e.target来检查iframe是否是单击事件的目标。e.target是对调度事件的对象的引用。

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

答案 2 :(得分:0)

您可能正在做这样的事情。

就“关闭” iframe而言,我不确定是否要hide/remove/slide移开它,但这只会切换其高度。

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