制作幻灯片

时间:2017-01-01 17:11:06

标签: javascript carousel

我正在一个动物救援的网站上工作,我正试图将一些动物的自动幻灯片放映,但是,对于我的生活,我无法让代码工作。有什么建议吗?

    <div class="photobanner" style="max-height:460px">
        <img class="myslides" src="image-1.jpg" style="height:100%" />
        <img class="myslides" src="image-2.jpg" style="height:100%" />
        <img class="myslides" src="image-3.jpg" style="height:100%" />
        <img class="myslides" src="image-4.jpg" style="height:100%" />
        <img class="myslides" src="image-5.jpg" style="height:100%" />
        <img class="myslides" src="image-6.jpg" style="height:100%" />
    </div>

    <script type="text/javascript">
var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("mySlides");
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";  
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}    
    x[myIndex-1].style.display = "block";  
    setTimeout(carousel, 2000); // Change image every 2 seconds
}
</script>

2 个答案:

答案 0 :(得分:2)

试试这个小提琴:https://jsfiddle.net/zaedmfLs/

var myIndex = 0;
setInterval(carousel, 2000);

function carousel() {
    var i;
    var x = document.getElementsByClassName("myslides");
    for (i = 0; i < x.length; i++) {
        console.log("Carousel");
       x[i].style.display = "none";  
    }
    myIndex++;

    if (myIndex > x.length) {myIndex = 1} 
    x[myIndex-1].style.display = "block";  
}

您的代码几乎没有变化:

  1. 使用setInterval而不是setTimeout
  2. setInterval调用是在carousel方法之外进行的,因为需要重复调​​用carousel。
  3. myslides名称中有拼写错误(上限&#39; S&#39;)

答案 1 :(得分:0)

您有两个主要问题:

  1. mySlidesmyslides不是一回事
  2. 而不是setTimeout我会使用setInterval每2秒调用一次函数
  3. 这是一个建议

    var myIndex = 0;
    var images = document.getElementsByClassName("myslides");
    setInterval(carousel, 2000); // Change image every 2 seconds
    
    function carousel() {
        images[myIndex].style.display = "none";  
    
        myIndex++;
        if (myIndex >= images.length) {
          myIndex = 0;
        }
        console.log(myIndex, images.length);
        images[myIndex].style.display = "block";  
    }
    img.myslides {
      display: None;
    }
        <div class="photobanner" style="max-height:460px">
            <img class="myslides" src="image-1.jpg" style="height:100%" />
            <img class="myslides" src="image-2.jpg" style="height:100%" />
            <img class="myslides" src="image-3.jpg" style="height:100%" />
            <img class="myslides" src="image-4.jpg" style="height:100%" />
            <img class="myslides" src="image-5.jpg" style="height:100%" />
            <img class="myslides" src="image-6.jpg" style="height:100%" />
        </div>