javascript 单击其外部关闭 DIV 弹出窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13787888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:47:43  来源:igfitidea点击:

Close DIV popup clicking outside of it

javascriptjquerycsshtmlpopup

提问by fabikus

I have this code and I want to close this <div>popup by clicking outside of it and not only by clicking on the close button.

我有这个代码,我想<div>通过点击它的外部而不是仅仅点击关闭按钮来关闭这个弹出窗口。

How can I do that?

我怎样才能做到这一点?

<script language="JavaScript">
 <!--
function displayPopup(alert_MSG) {

    var theDetail = document.getElementById(alert_MSG);
        theDetail.style.display="block";
}

function closePopup(alert_MSG) {

    var theDetail = document.getElementById(alert_MSG);

    if (theDetail.style.display=="block") {
        theDetail.style.display="none";
    }
}
-->
</script>

Here is the HTML link:

这是 HTML 链接:

<a href="javascript:displayPopup(<?=$id_pic?>)">open div here</a>

And is here my popup:

这是我的弹出窗口:

<div id="<?=$id_pic?>" class="myPopup" style="display:none;">
<div class="closeButton">
<a href="javascript:closePopup(<?=$id_pic?>)">Close</a>
</div>
Popup content here
</div>

回答by AspiringCanadian

$(document).click(function(event) {
    if ( $(event.target).closest(".myPopup").get(0) == null ) {         
    alert('clicked outside');           
    } else{
    alert('clicked inside');
    }
});

This works for me.

这对我有用。

回答by EricG

Watch this for webkit. CodePen.IO

看看这个 webkit。代码笔

#overlay {
  top: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: red;
  z-index: 40;
}

With:

和:

document.getElementById("overlay").addEventListener("click", closePopup, false );
document.getElementById("popup").addEventListener("click", stopPropagation, false );

回答by Akhil Sekharan

Try:

尝试:

document.onmousedown = function(){
    if(event.target.className != 'myPopup')
        document.getElementsByClassName('myPopup')[0].style.display = 'none';
}

回答by ParPar

$('body').click(function(){
   $(".myPopup").hide();
});

Edit:

编辑:

Maybe you can wrap your code in this:

也许你可以把你的代码包装成这样:

<body>
   <a href="javascript:closePopup(<?=$id_pic?>)" style="curser:default">
      // all your code
   </a>
</body>