未捕获的类型错误:无法读取图像滑块未定义的属性“样式”

时间:2021-03-15 23:42:01

标签: javascript html css

我正在制作一个简单的图片滑块,您点击它,它就会移动到下一张图片。这是通过在单击时更改图像的 z-index 来完成的。出于某种原因,现在我已将其加载到我的托管站点中,但我在 Google Chrome 控制台上收到错误消息:“Uncaught TypeError: Cannot read property 'style' of undefined”。

错误特别发生在倒数第二行:“z=images[currentSlide].style.zIndex”知道如何解决这个问题吗?

这是相关的 HTML 和 JS:

<section class="fixed-container wrap">

  <div class="logo-bg">
    </div>
    
    <div class="slider">
        <img src="https://upload.wikimedia.org/wikipedia/commons/e/e5/Golden_rectangle.png">
        <img src="https://i0.wp.com/mathblog.wpengine.com/wp-content/uploads/2017/03/image005.gif?zoom=2.625&resize=364%2C222&ssl=1">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Rectangle_example.svg/1024px-Rectangle_example.svg.png">
    </div>
</section>
<!--tags-->
const slideArea = document.querySelector("div.slider")
const images = slideArea.querySelectorAll("img")

<!--we want to keep track of two things-->
let currentSlide = 0
let z = 1

<!--when I click the slide area I want to change the slide based on the z-index-->
wrap.addEventListener('click', function(e){

const width = +getComputedStyle(document.body).width.slice(0, -2) / 2;

if (e.pageX <= width){
    currentSlide = currentSlide - 1
    if(currentSlide < 0){
    currentSlide = images.length
}
    z= z + 1} 
else{
        currentSlide = currentSlide + 1
        if(currentSlide > images.length - 1){
        currentSlide = 0
    }
        z=z + 1}


<!--remove animation from the style for every image-->
images.forEach(image =>{
image.style.animation=""
})

z=images[currentSlide].style.zIndex
images[currentSlide].style.animation="fade .5s"
})

1 个答案:

答案 0 :(得分:1)

问题很可能来自currentSlide = images.length

索引从零开始,所以 images[images.length] 将是未定义的。最后一个索引比长度少一个。

尝试更改为:

currentSlide = images.length - 1;