如何使此滑块自动播放?

2022-01-24 00:00:00 slider javascript playback

我试图让这个滑块在 Javascript (jquery) 中自动播放,但我似乎无法让它工作,有谁知道我可以如何实现这一点?每次我尝试某些东西时,它似乎都会破坏滑块按钮.

I am trying to get this slider to auto play in Javascript (jquery) but I can't seem to get it to work, Does anyone know how I can achieve this? Every time I tried something it seemed to break the slider buttons.

jsfiddle 版本:http://jsfiddle.net/EsdB7/5/

jsfiddle version: http://jsfiddle.net/EsdB7/5/

这是当前代码:

jQuery(document).ready(function ($) {

    var slideCount = $('#slider ul li').length;
    var slideWidth = $('#slider ul li').width();
    var slideHeight = $('#slider ul li').height();
    var sliderUlWidth = slideCount * slideWidth;

    $('#slider').css({ width: slideWidth, height: slideHeight });

    $('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });

    $('#slider ul li:last-child').prependTo('#slider ul');

    function moveLeft() {
        $('#slider ul').animate({
            left: + slideWidth
        }, 200, function () {
            $('#slider ul li:last-child').prependTo('#slider ul');
            $('#slider ul').css('left', '');
        });
    };

    function moveRight() {
        $('#slider ul').animate({
            left: - slideWidth
        }, 200, function () {
            $('#slider ul li:first-child').appendTo('#slider ul');
            $('#slider ul').css('left', '');
        });
    };

    $('a.control_prev').click(function () {
        moveLeft();
    });

    $('a.control_next').click(function () {
        moveRight();
    });

});    

推荐答案

尼尔的回答 是正确的,但如果你想它会在页面加载时自动播放,您可以将其添加到变量声明中:

Neil's answer is correct, but if you want it to automatically play when the page loads, you can add this to your variable declarations:

var auto = setInterval(moveRight, 1000); // 1000 ms = 1 sec

像这样:

var slideCount = $('#slider ul li').length;
var slideWidth = $('#slider ul li').width();
var slideHeight = $('#slider ul li').height();
var sliderUlWidth = slideCount * slideWidth;
var auto = setInterval(moveRight, 1000); // 1000 ms = 1 sec

相关文章