单击添加类然后在div外部单击时删除一个类?

时间:2018-02-13 12:50:06

标签: javascript jquery

我从这里的答案中尝试了所有方法,但没有奏效。 到目前为止,我已经完成了:

jQuery(function($) {
  $(document).ready(function(){
      $("#sb-search").click(function(){
          $(".sb-search").addClass("sb-search-open");
          $("body").click(function(){
              $(".sb-search").hasClass("sb-search-open");
              $(this).removeClass("sb-search-open");
          });
      });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="sb-search" class="sb-search">
    <form autocomplete="off" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
        <input class="sb-search-input" type="search" value="" name="s" id="s">
        <input class="sb-search-submit" type="submit" value="">
        <span class="sb-icon-search"></span>
    </form>
</div>
</body>

我想在div之外点击

后删除.sb-search-open

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
jQuery(function($) {
  $(document).ready(function(){
      $("#sb-search").click(function(e){
           e.stopPropagation();
          $(".sb-search").addClass("sb-search-open");

      });
      $("body").click(function(){
              $(".sb-search").removeClass("sb-search-open");
              console.log('body')
       });
  });
});
&#13;
html,body{
  height:100%;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="sb-search" class="sb-search">
    <form autocomplete="off" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
        <input class="sb-search-input" type="search" value="" name="s" id="s">
        <input class="sb-search-submit" type="submit" value="">
        <span class="sb-icon-search"></span>
    </form>
</div>
</body>
&#13;
&#13;
&#13;

首先删除输入单击侦听器的主体外侧的单击侦听器。 在输入单击侦听器中添加e.stopPropagation()以停止事件冒泡

jQuery(function($) {
  $(document).ready(function(){
      $("#sb-search").click(function(e){
           e.preventDefault();
           e.stopPropagation();
          $(".sb-search").addClass("sb-search-open");

      });
      $("body").click(function(){
              $(".sb-search").removeClass("sb-search-open");
       });
  });
});