簡體   English   中英

在外部點擊時關閉iframe

[英]Close iframe when click outside

我在外面單擊時如何關閉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>

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

使用Jquery is()和e.target(這是對調度事件的對象的引用)檢查iframe是否是單擊事件的目標。

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

您可能正在做這樣的事情。

在“關閉” 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