有一个问题,当我创建此幻灯片的多个实例时,似乎只有一个实例可以工作。不确定如何重新格式化它,以便它适用于多个实例。
JavaScript
//SLIDESHOW
const slideshow = document.querySelector("section.slideshow")
const images = slideshow.querySelectorAll("img")
slideshow.addEventListener("mousemove", function (event) {
const x = event.offsetX
const width = this.offsetWidth
const percentage = x / width
const imageNumber = Math.floor(percentage * images.length)
images.forEach(image => {
image.style.zIndex = 0
})
images[imageNumber].style.zIndex = 1
})
HTML
<section class ="slideshow">
<img src="assets/images/1.png">
<img src="assets/images/3.png">
<img src="assets/images/2.png">
</section>
最佳答案
document.querySelector("section.slideshow")
将始终选择第一个 <section class="slideshow">
它遇到的元素。
如果您希望相同的代码能够处理多个幻灯片元素,则需要将它们全部选择到 NodeList
中。并为每个实例运行初始化代码。
应该是这样的:(未经测试)
const slideshow_instances = document.querySelectorAll("section.slideshow")
for (var i = 0; i < slideshow_instances.length; i++) {
const slideshow = slideshow_instances[i];
const images = slideshow.querySelectorAll("img")
slideshow.addEventListener("mousemove", function (event) {
const x = event.offsetX
const width = this.offsetWidth
const percentage = x / width
const imageNumber = Math.floor(percentage * images.length)
images.forEach(image => {
image.style.zIndex = 0
})
images[imageNumber].style.zIndex = 1
})
}
关于javascript - 幻灯片的多个实例破坏了代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54951240/