如果隐藏了父母,是否可以计算可见的孩子?

时间:2018-08-03 02:20:46

标签: javascript jquery css3

我不知道是否可以这样做...所以我想要一个解释。

我有这种情况:

   <div id="grandfather" style="display:none">
    <div id="ipocentro-quakes">
      <div></div>
      <div></div>
      <div style="display:none"></div>
      <div></div>
    </div>
   </div>

    var selezioni_attive= ($('#ipocentro-quakes > div:visible').length)-1;

我会输出类似 2 的信息,因为计算时我不会考虑第一个孩子和所有隐藏的孩子(在我的情况下只有一个,第三个)。

但是我的输出是 -1

如果#grandfather中有display:none,也可以这样做吗?

非常感谢,对不起我的英语

4 个答案:

答案 0 :(得分:2)

您需要使用:not(:firstchild)跳过第一个元素,并使用not([style*="display: none"])跳过带有display:none的元素:

var selezioni_attive = 
    ($('#ipocentro-quakes > div:not(:firstchild):not([style*="display: none"])').length)-1;

答案 1 :(得分:0)

您可以检索并列出子级列表,逐一检查每个子级元素的可见性:

在Vanila JS中:

let count = 0;
let parent = document.getElementById('ipocentro-quakes');
Array.from(parent.children).forEach( e=>{
  // get child index
  let index = Array.prototype.indexOf.call(parent.children, e);
  // ignore first child
  if(index===0)  return;
  // get style of child
  var style = window.getComputedStyle(e);
  // if it's visible, increase counter
  if (style.display !== 'none') count++;
})
console.log('total visible:',count)
<div id="grandfather" style="display:none">
  <div id="ipocentro-quakes">
    <div></div>
    <div></div>
    <div style="display:none"></div>
    <div></div>
  </div>
 </div>

紧凑版

由@ Jaromanda-X在评论中提供

let count = Array.from(parent.children).slice(1).filter(e => window.getComputedStyle(e).display !== 'none').length;

答案 2 :(得分:0)

jQuery文档显示为:

  

如果元素占用了文档中的空间,则认为它们是可见的。可见元素的宽度或高度大于零。

https://api.jquery.com/visible-selector/

由于div的父级为display:none,因此它们也将不占用空间,因此被视为不可见

如何使用类名

$(document).ready(function() {
  var selezioni_attive = $("#ipocentro-quakes > div:not(.invisible)").length;

  console.log(selezioni_attive);
});
.invisible {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grandfather" style="display:none">
  <div id="ipocentro-quakes">
    <div></div>
    <div></div>
    <div class="invisible"></div>
    <div></div>
  </div>
</div>

答案 3 :(得分:0)

是的,有可能:

let found = $('#grandfather')
              .find(':not(:first-child)')
              .filter((i, el) => el.style.display != 'none')
              .length;

console.log(found)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grandfather" style="display:none">
  <div id="ipocentro-quakes">
    <div></div>
    <div></div>
    <div style="display:none"></div>
    <div></div>
  </div>
</div>

  • 选择祖先
  • 找到不是第一个孩子的一切
  • 这些
  • 仅过滤掉可见的那些
相关问题