【问题标题】:Close DIV popup clicking outside of it关闭 DIV 弹出窗口在其外部单击
【发布时间】:2012-12-10 16:52:19
【问题描述】:

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

【问题讨论】:

  • 是弹出模式(用户在打开时不能点击其他任何东西)?如果是这样,您可以在弹出窗口下方(以及其他所有内容之上)放置一个整页透明 div。然后在透明div中添加onclick事件处理函数来关闭弹窗(类似于在body标签中添加onclick事件处理函数,但不太可能引起冲突)。您必须跟踪当前打开的弹出窗口,以便知道要关闭哪个弹出窗口。
  • 您应该在弹出窗口 (100%x100%) 正下方使用(不可见的)叠加层,以捕捉弹出窗口之外的任何点击。如果你不使用它,那么其他元素可能会停止传播事件,那么下面的解决方案将不会总是有效。添加你自己的 jsFiddle 会很有帮助,因为人们并不总是有时间将你的情况与你的代码集成。

标签: javascript jquery css html popup


【解决方案1】:
$(document).click(function(event) {
    if ( $(event.target).closest(".myPopup").get(0) == null ) {         
    alert('clicked outside');           
    } else{
    alert('clicked inside');
    }
});

这对我有用。

【讨论】:

  • 我真的很喜欢这种方法。
【解决方案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 );

【讨论】:

    【解决方案3】:

    试试:

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

    【讨论】:

      【解决方案4】:
      $('body').click(function(){
         $(".myPopup").hide();
      });
      

      编辑:

      也许你可以把你的代码包装在这个:

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

      【讨论】:

      • @fabikus 如果该功能总是关闭当前弹出窗口 - 看看我的版本是否对您有帮助
      猜你喜欢
      • 2021-11-21
      • 2023-02-09
      • 2012-12-21
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多