如何不将toggle()应用于已经具有display:none的div元素?

时间:2015-09-20 14:05:42

标签: javascript jquery html css

我正在尝试将slideToggle()jQuery函数用于我的网页。

有些div元素已经具有“display:none”样式。 这些元素将来可以使用,所以我只是让它们不显示。 问题是这些元素也会响应切换方法,这样每当我点击按钮时,它也会出现并且很快消失但很难看。我不希望这些元素被显示出来。

以下是简化的示例。

$(document).ready(function(){
  
  var toggleBtn = $(".toggle-button");
  toggleBtn.click(function(){
    $(this).parent().find("div:not('.toggle-button')").slideToggle(); 
    });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="toggle-button">Click</div>
  
  <div class="need-toggle-A">A</div>
  <div class="need-toggle-B">B</div>
  <div class="need-toggle-C">C</div>
  <div class="need-toggle-D">
    <div class="need-no-toggle-A" style="display:none">Please Don't show me!</div>
    <div class="need-no-toggle-B" style="display:none">Please Don't show me!!</div>
    <div class="need-no-toggle-C" style="display:none">Please Don't show me!!!</div>
    
  </div>
  
</div>

3 个答案:

答案 0 :(得分:3)

您可以在里面使用额外的:not()来仅选择不包含类need-no-toggle的元素

:not([class*='need-no-toggle'])

class* = 'need-no-toggle检查元素包含need-no-toggle

有关class*=的详细信息,请阅读此css-tricks

$(document).ready(function(){
  
  var toggleBtn = $(".toggle-button");
  toggleBtn.click(function(){
    $(this).parent().find("div:not('.toggle-button'):not([class*='need-no-toggle'])").slideToggle(); 
    });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="toggle-button">Click</div>
  
  <div class="need-toggle-A">A</div>
  <div class="need-toggle-B">B</div>
  <div class="need-toggle-C">C</div>
  <div class="need-toggle-D">
    <div class="need-no-toggle-A" style="display:none">Please Don't show me!</div>
    <div class="need-no-toggle-B" style="display:none">Please Don't show me!!</div>
    <div class="need-no-toggle-C" style="display:none">Please Don't show me!!!</div>
    
  </div>
  
</div>

答案 1 :(得分:1)

您可以使用相同的班级名称来切换

 <div class="need-toggle-A need-toggle">A</div>
  <div class="need-toggle-B need-toggle">B</div>
  <div class="need-toggle-C need-toggle">C</div>

然后单独切换

  $(this).parent().find(".need-toggle").slideToggle(); 

的jsfiddle https://jsfiddle.net/nznrru01/

答案 2 :(得分:0)

另一个解决方案是,为了使代码清晰,您应该重命名该类,以便将要切换的部分与您不想要的部分区分开来。例如:

<div class="wrapper">
  <div class="toggle-button">Click</div>

  <div class="need-toggle-A">A</div>
  <div class="need-toggle-B">B</div>
  <div class="need-toggle-C">C</div>
  <div class="need-no-toggle"> <!-- Change class name here -->
    <div class="need-no-toggle-A" style="display:none">Please Don't show me!</div>
    <div class="need-no-toggle-B" style="display:none">Please Don't show me!!</div>
    <div class="need-no-toggle-C" style="display:none">Please Don't show me!!!</div>

  </div>

</div>

然后,您可以在div[class^='need-toggle']函数中使用此选择器:find()