【问题标题】:clicking outside the div inside div should be close在 div 里面点击 div 应该是关闭的
【发布时间】:2013-12-12 17:53:50
【问题描述】:

我尝试使用此代码打开内部 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/

【问题讨论】:

  • 所以您希望在.userNameBox 之外的点击关闭.profile
  • 您的代码捕获了 div 内部的点击 - 您没有外部处理程序(除非您在代码中的其他地方有它)。
  • 外部表示文件...

标签: javascript jquery html


【解决方案1】:

监听body,看看点击是从哪里来的

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

【讨论】:

    【解决方案2】:

    我认为最好的解决方案是在主体上添加一个事件,该事件将在单击时隐藏配置文件,并在您的 userNameBox 函数中停止事件传播。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多