在滚动时显示每个图像的计数可以通过以下步骤实现:
以下是一个示例代码:
HTML:
<div id="image-container">
<img src="image1.jpg" data-img-id="1" alt="Image 1">
<img src="image2.jpg" data-img-id="2" alt="Image 2">
<img src="image3.jpg" data-img-id="3" alt="Image 3">
<!-- 更多图像... -->
</div>
CSS:
#image-container {
width: 400px;
height: 200px;
overflow: scroll;
position: relative;
}
.image-count {
position: absolute;
top: 10px;
right: 10px;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
padding: 5px;
border-radius: 5px;
}
JavaScript:
var imageContainer = document.getElementById('image-container');
imageContainer.addEventListener('scroll', function() {
var images = imageContainer.getElementsByTagName('img');
var containerTop = imageContainer.getBoundingClientRect().top;
var containerHeight = imageContainer.offsetHeight;
for (var i = 0; i < images.length; i++) {
var image = images[i];
var imageRect = image.getBoundingClientRect();
var imageTop = imageRect.top - containerTop;
var imageBottom = imageTop + imageRect.height;
if (imageBottom >= 0 && imageTop <= containerHeight) {
// 图像在可见范围内
var imgId = image.getAttribute('data-img-id');
var countElement = document.createElement('span');
countElement.className = 'image-count';
countElement.innerText = 'Image ' + imgId;
imageContainer.appendChild(countElement);
} else {
// 图像不在可见范围内
var countElements = imageContainer.getElementsByClassName('image-count');
for (var j = 0; j < countElements.length; j++) {
imageContainer.removeChild(countElements[j]);
}
}
}
});
这个示例代码实现了在滚动时显示每个图像的计数。当图像进入可见范围时,会在图像上方显示相应的计数标签,当图像离开可见范围时,计数标签会被隐藏。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云