【问题标题】:If all divs have same style, remove element如果所有 div 具有相同的样式,则删除元素
【发布时间】:2019-11-08 11:31:15
【问题描述】:

我有多个具有相同名称的 div,我想检查所有 div 是否具有显示样式:无;然后另一个 div 也会隐藏。密码笔:- https://codepen.io/scottYg55/pen/OexpgR `

jQuery(".tile").each(function () {
  if (jQuery(this).css("display") == "none") { 
    $(".hideme").hide(); 
  }
});
.tiles {
  width:100%;
  height:100%;
}

.tile {
  width:100%;
  height:200px;
  background:red;
}
<div class="tiles">
  <div class="tile" style="display: none">Test</div>
  <div class="tile" style="display: none">Test</div>
  <div class="tile" style="display: none">Test</div>
  <div class="tile" style="display: none">Test</div>
  <div class="tile" style="display: none">Test</div>
  <div class="tile" style="display: none">Test</div>
</div>

Jquery 仅在 1 个 div 具有这种样式时才有效,我希望这个 hideme div 在所有 div 都具有这种样式时隐藏

【问题讨论】:

    标签: jquery html css


    【解决方案1】:

    您可以使用filter() 来检查:visible 元素:

    function checkVisibility() {
      var allHidden = $('.tile').filter(':visible').length === 0;
      $('.hideme').toggle(!allHidden);
    }
    
    // Toggle the first element on button click and run the check
    $('#toggleStyle').on('click', function() {
      $('.tile').first().toggle();
      checkVisibility();
    })
    
    checkVisibility();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
    
    <button id="toggleStyle" type="button">Toggle Style</button>
    
    <div class="tiles">
      <div class="tile" style="display:none">Test</div>
      <div class="tile" style="display:none">Test</div>
      <div class="tile" style="display:none">Test</div>
      <div class="tile" style="display:none">Test</div>
      <div class="tile" style="display:none">Test</div>
      <div class="tile" style="display:none">Test</div>
    </div>
    
    <div class="hideme">Hide Me!</div>

    【讨论】:

    • 这可以在 dom 元素上工作吗?我有一个添加样式的过滤器
    • 每次过滤器改变样式时运行上述代码
    • 这是我尝试使用的代码。 var selectedClass = ""; $(".blogfilter a").on('click', function(){ $(".blogfilter a").removeClass("filter-selected"); $(".tiles .tile").addClass("两块瓷砖"); $(this).addClass("filter-selected"); selectedClass = $(this).attr("data-rel"); $("#blog-posts").fadeTo(100, 0.1); $("#blog-posts .tile").not("."+selectedClass).fadeOut().removeClass('scale-anm'); setTimeout(function() { $("."+selectedClass ).fadeIn().addClass('scale-anm'); $("#blog-posts").fadeTo(300, 1); }, 300); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多