幻灯片代码在Javascript中不起作用

时间:2018-12-07 17:12:39

标签: javascript debugging slideshow

我做了幻灯片放映。这是HTML代码!

<div class="slideshow-container">
    <div class="mySlides fade">
        <img src="img/background.png" style="width:100%">
    </div>
    <div class="mySlides fade">
        <img src="img/background2.png" style="width:100%">
    </div>
    <div class="mySlides fade">
        <img src="img/background3.png" style="width:100%">
    </div>
    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>

</div>

这是JavaScript代码

<script>
    var slideIndex = 1;
    showSlides(slideIndex);

    function plusSlides(n) {
        showSlides(slideIndex += n); 
    }

    function showSlides(slideIndex) {
        var i;
        var slides = document.getElementsByClassName("mySlides");

        if (slideIndex > slides.length) { slideIndex = 1; }
        if (slideIndex < 1) { slideIndex = slides.length; }

        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        slides[slideIndex - 1].style.display = "block"; 
    }
</script>

但是由于某些未知原因,它无法正常运行,请调试并解释为什么此代码无法正常工作?

1 个答案:

答案 0 :(得分:0)

您两次定义了索引变量:slideIndex。一次作为全局变量,然后作为函数参数,仅覆盖函数参数值。您可以在plusSlides函数中删除函数参数并增加/减小slideIndex值。

var slideIndex = 1;
showSlides();

function plusSlides(n) {
  slideIndex += n;
    showSlides(); 
}

function showSlides() {

    var slides = document.getElementsByClassName("mySlides");

    if (slideIndex > slides.length) { slideIndex = 1; }
    if (slideIndex < 1) { slideIndex = slides.length; }

    for (var i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
    }
    slides[slideIndex - 1].style.display = "block"; 
}