我正在使用 slick js 通过幻灯片显示项目。每张幻灯片都有 1 张较大的特色图片和 3 张较小的缩略图。
当缩略图悬停时,会添加“thumbnail-active”类,将其从前一个中删除,缩略图显示为特色图片。
问题是这仅适用于第一张幻灯片。我试图获取当前幻灯片并在每次更改幻灯片时重新应用该功能,但它似乎不起作用。 还有其他方法吗?
这里是js:
<div class="img-wrapper">
<div class="slide-wrapper">
<img class="thumbnail thumbnail-active" src="https://images.pexels.com/photos/4937452/pexels-photo-4937452.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="">
<img class="thumbnail" src="https://images.pexels.com/photos/4937448/pexels-photo-4937448.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="">
<img class="thumbnail" src="https://images.pexels.com/photos/4937360/pexels-photo-4937360.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="">
</div>
<img id="featured" src="https://images.pexels.com/photos/4937452/pexels-photo-4937452.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="">
</div>
let thumbnails = document.getElementsByClassName('thumbnail')
let activeImages = document.getElementsByClassName('thumbnail-active')
for (var i = 0; i < thumbnails.length; i++) {
thumbnails[i].addEventListener('mouseover', function() {
if (activeImages.length > 0) {
activeImages[0].classList.remove('thumbnail-active')
}
this.classList.add('thumbnail-active')
document.getElementById('featured').src = this.src
})
}
答案 0 :(得分:0)
您需要将 id #featured
替换为 .featured
,然后尝试使用以下行替换代码
//document.getElementById('featured').src = this.src; //old code
this.parentNode.parentNode.querySelector('.featured').src = this.src; // new line
答案 1 :(得分:0)
@Onkar 是对的。这是因为重复的 ID。
你可以这样做:
document.querySelector('.slick-current #featured').src = this.src;
slick 会向当前幻灯片添加一个名为 slick-current 的类。
最好在脚本中用 .featured 替换 #featured,并使用 features as class 而不是 id。