如何让这个滑块自动播放?

时间:2013-10-28 21:54:41

标签: javascript slider playback

我试图让这个滑块在Javascript(jquery)中自动播放,但我似乎无法让它工作,有谁知道我怎么能实现这个?每当我尝试某些东西时,它似乎都会打破滑块按钮。

jsfiddle版本: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();
    });

});    

2 个答案:

答案 0 :(得分:1)

Neil's answer是正确的,但如果您希望它在页面加载时自动播放,您可以将其添加到变量声明中:

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

答案 1 :(得分:0)

只需添加以下代码 -

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

之后:

$('a.control_next').click(function () {
    moveRight();
});
 //any where after the declaration of moveRight function.
发生的事情是,每隔1000毫秒就会调用moveRight函数 JS FIDDLE of the edited code