2

我有这段代码,我想<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>
4

4 回答 4

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

这对我有用。

于 2012-12-10T08:25:26.317 回答
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 );
于 2012-12-10T08:52:19.843 回答
0

Try:

document.onmousedown = function(){
    if(event.target.className != 'myPopup')
        document.getElementsByClassName('myPopup')[0].style.display = 'none';
}
于 2012-12-09T13:42:07.693 回答
0
$('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>
于 2012-12-09T13:44:52.830 回答