首頁>Program>source

我想通過單击div中的關闭鏈接来隱藏div, or 通過點击该div以外的任何地方。

我正在尝試遵循以下代碼,它可以通過正確單击關闭鏈接来打開和關闭div,但是如果我無法通過單击div以外的任何位置来關闭它,則可以關闭。

$(".link").click(function() {
  $(".popup").fadeIn(300);
}
);
$('.close').click(function() {
  $(".popup").fadeOut(300);
}
);
$('body').click(function() {
  if (!$(this.target).is('.popup')) {
    $(".popup").hide();
  }
}
);
<div class="box">
  <a href="#" class="link">Open</a>
  <div class="popup">
    Hello world
    <a class="close" href="#">Close</a>
  </div>
</div>

Demo: http://jsfiddle.net/LxauG/

最新回復
  • 5月前
    1 #

    另一種方法則是 您的jsfiddle越野車少(需要双击打開)。

    這不会在主體級別使用任何委託事件

    Set tabindex="-1" 到DIV .popup(以及樣式CSS outline:0

    演示

    $(".link").click(function(e){
        e.preventDefault();
        $(".popup").fadeIn(300,function(){$(this).focus();});
    });
    $('.close').click(function() {
       $(".popup").fadeOut(300);
    });
    $(".popup").on('blur',function(){
        $(this).fadeOut(300);
    });
    

  • 5月前
    2 #

    您需要

    $('body').click(function(e) {
        if (!$(e.target).closest('.popup').length){
            $(".popup").hide();
        }
    });
    

  • 5月前
    3 #

    我建議使用stopPropagation()方法,如修改後的小提琴所示:

    提琴

    $('body').click(function() {
        $(".popup").hide();
    });
    $('.popup').click(function(e) {
        e.stopPropagation();
    });
    

    這樣,您可以在單击主體時隱藏弹出視窗,而無需添加額外的if,並且当您單击弹出視窗時,事件不会通過弹出視窗弹出到主體. / p>

  • 5月前
    4 #

    您最好選擇類似這樣的东西.只需给要隱藏的div輸入一个id,然後建立一个類似這樣的函式即可。 通過在正文上添加onclick事件来呼叫此函式。

    function myFunction(event) { 
    if(event.target.id!="target_id")
    { 
        document.getElementById("target_id").style.display="none";
      }
    }
    

  • 5月前
    5 #

    添加一个透明背景,该背景占据整个視窗的大小,就在弹出div之前

    .transparent-back{
        position: fixed;
        top: 0px;
        left:0px;
        width: 100%;
        height: 100%;
        background-color: rgba(255,255,255,0.5);
    }
    

    然後單击它,關闭弹出視窗。

    $(".transparent-back").on('click',function(){
        $('popup').fadeOut(300);
    });
    

  • 64 bit:如何在JavaScript中對大於32位的變數进行按位与運算?
  • url:如何使用file:方案在html中指定本地檔案?