我有一个相册,不应在开始时显示所有照片,并显示不包含在相册中的照片数量(我使用
overflow: hidden;
。
看过this answer之后,我决定这样做:
const a = document.querySelectorAll('a')
const count = 0
a.forEach(el => {
if (isHidden(el))
count++
})
console.log('Hidden elemenets: ' + count)
function isHidden (el) {
return el.offsetParent === null
}
#lightgallery {
overflow: hidden;
margin-top: 30px;
height: 122px;
position: relative; /* important */
}
#lightgallery a {
width: 176px;
display: inline-block;
}
#lightgallery img {
width: 100%;
}
#lightgallery a {
color: transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lightgallery">
<a href="assets/img/light1.jpg">
<img src="https://picsum.photos/200/300/?random=1">
</a>
<a href="assets/img/light2.jpg">
<img src="https://picsum.photos/200/300/?random=2">
</a>
<a href="assets/img/light3.jpg">
<img src="https://picsum.photos/200/300/?random=3">
</a>
<a href="assets/img/light4.jpg">
<img src="https://picsum.photos/200/300/?random=4">
</a>
<a href="assets/img/light5.jpg">
<img src="https://picsum.photos/200/300/?random=5">
</a>
<a href="assets/img/light4.jpg">
<img src="https://picsum.photos/200/300/?random=6">
</a>
<a href="assets/img/light5.jpg">
<img src="https://picsum.photos/200/300/?random=7">
</a>
</div>
但是它不起作用。
我需要计算屏幕上不可见的照片。我采用响应式设计,因此图库元素可以具有不同的大小,因此不同的用户可以拥有不同数量的照片。
答案 0 :(得分:2)
您可以使用class
来做到这一点(我认为以这种方式这样做要简单得多)。
const a = document.querySelectorAll('.img-hidden')
console.log(a.length);
#lightgallery {
overflow: hidden;
margin-top: 30px;
height: 122px;
position: relative; /* important */
}
#lightgallery a {
width: 176px;
display: inline-block;
}
#lightgallery img {
width: 176px;
}
#lightgallery a {
color: transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lightgallery">
<a href="assets/img/light1.jpg" class="img-visible">
<img src="https://picsum.photos/200/300/?random=1">
</a>
<a href="assets/img/light2.jpg" class="img-visible">
<img src="https://picsum.photos/200/300/?random=2">
</a>
<a href="assets/img/light3.jpg" class="img-visible">
<img src="https://picsum.photos/200/300/?random=3">
</a>
<a href="assets/img/light4.jpg" class="img-visible">
<img src="https://picsum.photos/200/300/?random=4">
</a>
<a href="assets/img/light5.jpg" class="img-visible">
<img src="https://picsum.photos/200/300/?random=5">
</a>
<a href="assets/img/light4.jpg" class="img-hidden">
<img src="https://picsum.photos/200/300/?random=6">
</a>
<a href="assets/img/light5.jpg" class="img-hidden">
<img src="https://picsum.photos/200/300/?random=7">
</a>
</div>
可以在this link上找到一种不同的,更具编程性的方法。为此,您应该显式设置图像的高度,这对于给定的用例可能并不理想,但确实可以做到这一点。