我有这段代码,我想通过点击它之外来关闭这个<div>
弹出窗口,而不仅仅是点击关闭按钮。
我该怎么做?
<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>
以下是HTML链接:
<a href="javascript:displayPopup(<?=$id_pic?>)">open div here</a>
这是我的弹出窗口:
<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>
答案 0 :(得分:4)
$(document).click(function(event) {
if ( $(event.target).closest(".myPopup").get(0) == null ) {
alert('clicked outside');
} else{
alert('clicked inside');
}
});
这适合我。
答案 1 :(得分:2)
关注webkit。 CodePen.IO
#overlay {
top: 0;
position: absolute;
width: 100%;
height: 100%;
background-color: red;
z-index: 40;
}
使用:
document.getElementById("overlay").addEventListener("click", closePopup, false );
document.getElementById("popup").addEventListener("click", stopPropagation, false );
答案 2 :(得分:0)
尝试:
document.onmousedown = function(){
if(event.target.className != 'myPopup')
document.getElementsByClassName('myPopup')[0].style.display = 'none';
}
答案 3 :(得分:0)
$('body').click(function(){
$(".myPopup").hide();
});
修改强>
也许您可以将代码包装在此:
<body>
<a href="javascript:closePopup(<?=$id_pic?>)" style="curser:default">
// all your code
</a>
</body>