在div里面的div外面点击应该是关闭的

时间:2013-12-12 17:53:50

标签: javascript jquery html

我尝试使用此代码打开内部div并关闭div。但我有问题,当我点击div外,然后它不是关闭。当我在div外面点击然后内部div应该关闭时,我需要帮助。

这是代码:

<div class="userNameBox">prashant birajdar
    <div class="profile" style="display:none" tabindex="-1">
       here is the code.        
    </div>
</div>

这里是js代码

$( ".userNameBox" ).click(function() {
  $( ".profile" ).toggle( "slow" );
});

这里是jsfiddel http://jsfiddle.net/prashantbirajdar123/tY2vU/

2 个答案:

答案 0 :(得分:2)

聆听身体并查看点击来自哪里

$(document).click(function(evt) {
  if($(evt.target).closest(".userNameBox").length===0 && $(".profile").is(":visible")) {
      $(".profile").slideUp( "slow" );
  }
});

答案 1 :(得分:1)

在我看来,最好的解决方案是在主体上添加一个事件,在点击时隐藏配置文件,在你的userNameBox函数中停止事件传播。

$( ".userNameBox" ).click(function(e) {
  e.stopPropagation();
  $( ".profile" ).toggle( "slow" );
});

$(document).click(function(e){
  $( ".profile" ).hide( "slow" );
});
相关问题