2016-08-11 62 views
1

我该如何自动滑动? 我已经做到了,所以你可以手动滑动它们,但我希望它们在同一时间移动。如何将JS添加到此代码中,以便它自动滑动?

var slideIndex = 1; 
showSlides(slideIndex); 

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

function currentSlide(n) { 
    showSlides(slideIndex = n); 
} 

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

    if (n > slides.length) { 
     slideIndex = 1 
    } 
    if (n < 1) { 
     slideIndex = slides.length 
    } 
    for (i = 0; i < slides.length; i++) { 
     slides[i].style.display = "none"; 
    } 
    slides[slideIndex - 1].style.display = "block"; 
    dots[slideIndex - 1].className += " active"; 
} 
}; 
+0

你能把这个放在工作[小提琴](https://jsfiddle.net/)吗? – wahwahwah

回答

0

您可以使用下面的代码使其工作。

var slideIndex = 1; 
    $(function() { 
     automaticSlider(); 
    }) 

    function automaticSlider() { 
     showSlides(slideIndex); 
     setInterval(function() { automaticSlider(); }, 1000) // 1000 is 1 sec before calling next slide. 
    } 

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

function currentSlide(n) { 
    showSlides(slideIndex = n); 
} 

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

    if (n > slides.length) { 
     slideIndex = 1 
    } 
    if (n < 1) { 
     slideIndex = slides.length 
    } 
    for (i = 0; i < slides.length; i++) { 
     slides[i].style.display = "none"; 
    } 
    slides[slideIndex - 1].style.display = "block"; 
    dots[slideIndex - 1].className += " active"; 
} 
}; 

调用函数automaticSlider()在载荷,然后设置间隔是称之为automaticSlider()函数1秒后。你可以根据你的说服来增加时间。

+0

在您的示例中'slideIndex'未被发现,并且索引不会递增或递减。 – empiric

+0

到目前为止还没有添加完整的代码,但现在是!更新了代码。 –

+0

谢谢! @nalinaggarwal – Valeriadg

相关问题