【问题标题】:Close a sliding div by clicking outside of it通过单击外部来关闭滑动 div
【发布时间】:2016-11-20 07:43:17
【问题描述】:

我花了几个小时来解决我的问题,但还没有解决:/

我制作了this pen,它工作正常。这是一个带有打开/关闭按钮的基本滑动菜单(基于此jsfiddle),但我喜欢添加一个功能,允许用户通过单击菜单外部的任何位置来关闭菜单。

代码如下:

HTML

<div class='header'>
  <span class='button'>&#9776;</span>
  <span class="logo">LOGO HERE</span>
</div>
<div class='side-panel'>
  <nav>
    <ul>
      <li><a href='#'>ITEM 1</a></li>
      <li><a href='#'>ITEM 2</a></li>
      <li><a href='#'>ITEM 3</a></li>
    </ul>
  </nav>
</div>
<div class='content'>CONTENT HERE</div>

JS

$('.button').click(function(){
  if($(this).hasClass('active')){
    $(this).removeClass('active');
      $(this).html("&#9776;");
    $('.side-panel').animate({
    right:"-220px"
    });
    $(this).animate({
    right:"0"
    });
  }
  else{
    $(this).addClass('active');
    $(this).html("&#9587;");
    $('.side-panel').animate({
    right:"0",
  });
  $('.button').animate({
    right:"220px"
  });
  }
});

我在这里发现了一些非常有趣的话题,我尝试添加这个:

$(document).click(function(){
  if ($('.button').hasClass('active')){
    $(this).removeClass('active');
  }
});

但是没有用。我对 Js 的了解是基本的(就像我的英语(对不起)),我很确定我离解决方案不远,但我已经花了 3 个多小时,我开始绝望了;)我希望我是足够清楚,但如果您需要更多详细信息,请随时询问。干杯,感谢您的帮助。

CODEPEN

【问题讨论】:

    标签: menu slide


    【解决方案1】:

    又快又脏:

    点击内容时就像按下按钮一样:

    $('.content').click(
        function() { 
          $(".button").click(); 
        });
    

    更好:

    从函数中的.button点击事件中提取代码并调用两次:

    $('.button').click(function(){
      showhide();
    });
    
    $('.content').click(function() { 
      showhide();
    });
    
    function showhide()
    {
      var $this = $(".button");
      if($this.hasClass('active')){
      $this.removeClass('active');
        $this.html("&#9776;");
      $('.side-panel').animate({
        right:"-220px"
      });
      $this.animate({
        right:"0"
      });
      }
      else{
      $this.addClass('active');
      $this.html("&#9587;");
      $('.side-panel').animate({
        right:"0",
      });
      $('.button').animate({
        right:"220px"
      });
      }
    }
    

    【讨论】:

    • 感谢杰克花时间回答我。两种解决方案都有效,但问题是页面中的任何点击现在都会打开菜单。我又花了 2 个小时来解决我的问题,终于找到了一个运行良好的解决方案 :) 再次感谢。
    【解决方案2】:

    我终于找到了解决办法。我刚刚添加了这个:

    $('.content').click(function() {
      if($('.button').hasClass('active')){
       $('.button').removeClass('active');
       $('.button').html("&#9776;");
       $('.side-panel').animate({
        right:"-220px"
      });
      $('.button').animate({
        right:"0"
      });
      } 
    });
    

    现在,任何点击内容都会关闭 div .side-panel

    【讨论】:

      猜你喜欢
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多