幻灯片放映的多个实例中断代码

时间:2019-03-01 19:36:47

标签: javascript slideshow onmousemove

有一个问题,当我创建此幻灯片的多个实例时,似乎只有一个实例有效。不知道如何重新格式化它,使其可用于多个实例。

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>

1 个答案:

答案 0 :(得分:1)

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

    })
}