【问题标题】:show and hide content by clicking button or background [duplicate]通过单击按钮或背景显示和隐藏内容[重复]
【发布时间】:2020-08-10 19:05:26
【问题描述】:

我试图制作一个内容,如果你点击一个按钮就会被查看,如果你再次点击那个按钮就会隐藏,如果你点击除了内容本身之外的其他任何地方,它也会隐藏。
如果你点击教程,就像www.w3schools.com 一样。
我的尝试是这样的:

$(":not(#content)").click 不起作用。但即便如此,它也会在内容不可见的情况下一直被触发。没有好的代码。

$(document).ready(function() {
  $("button").click(function() {
    $("#content").toggle();

  });
  $(":not(#content)").click(function() {
    $("#content").hide();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">This is the Content</div>

<button>switch</button>

<div> This is somewhere else </div>

【问题讨论】:

标签: javascript html jquery


【解决方案1】:

如果单击的元素不是按钮或包含在内容中,您可以向隐藏内容的文档添加单击事件侦听器。

$(document).ready(function() {
  $("button").click(function() {
    $("#content").toggle();
  });
  $(document).click(function(e) {
    if(!$(e.target).closest('button, #content').length){
      $('#content').hide();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" style="display: none;">This is the Content</div>
<button>switch</button>
<div> This is somewhere else </div>

【讨论】:

    【解决方案2】:

    内容不再显示,因为当您单击“切换”时会触发这两个事件。如果您需要阻止另一个外部点击事件,请使用event.stopPropagation()event.cancelBubble = true

    评论这两行,你会看到区别。

    $(document).ready(function(){
      $("button").click(function(event){
        console.log("click button");
         event.stopPropagation();
         event.cancelBubble=true; 
        $("#content").toggle();
        
      });
      $("body").click(function(){
        console.log("click outside");
        $("#content").hide();
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="content">This is the Content</div>
    
    <button>switch</button>
    
    <div> This is somewhere else </div>

    【讨论】:

    • $event.stopPropagation();如果“$”在前面,它也适用于在运行时创建的按钮。 $(document).ready(function(){ $(document).on('click', '.sorting', function(){ //$(".sorting").on('click', function() { //$("button").click(function(){ alert("点击了按钮"); $(this).after(''); $event.stopPropagation(); }); //$(document).on('click', document, function(){ $(document).click(function() { alert("document was clicked"); } ); });
    猜你喜欢
    • 2017-08-28
    • 2017-08-11
    • 2010-11-18
    • 2021-03-19
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    相关资源
    最近更新 更多