0

我的javascript非常基础,我正在寻找正确方向的推动

我刚刚制作了一个简单的滑块,单击时效果很好。但我现在被要求让它自动循环播放幻灯片。

你能建议我应该看什么样的功能吗?

我在 codepen 上放了我的代码的工作副本:http: //codepen.io/DeadWhisky/pen/kvytH

这是javascript:

$("#kickstart").click(function () {
    document.getElementById("slider-ul").style.top="0px";
    document.getElementById("slider-nav").style.background="url(http://dev.learningpeople.co.uk/imgs/entry-it/slider-nav.png) repeat-y 0 -201px";
});

$("#support").click(function () {
    document.getElementById("slider-ul").style.top="-160px";
    document.getElementById("slider-nav").style.background="url(http://dev.learningpeople.co.uk/imgs/entry-it/slider-nav.png) repeat-y 0 -161px";        
});

$("#security").click(function () {
    document.getElementById("slider-ul").style.top="-320px";
    document.getElementById("slider-nav").style.background="url(http://dev.learningpeople.co.uk/imgs/entry-it/slider-nav.png) repeat-y 0 -121px";
});

$("#network").click(function () {
    document.getElementById("slider-ul").style.top="-480px";
    document.getElementById("slider-nav").style.background="url(http://dev.learningpeople.co.uk/imgs/entry-it/slider-nav.png) repeat-y 0 -81px";        
});

$("#slider-nav li").click(function() {
    $("#slider-nav li").removeClass("selected");
    $(this).addClass("selected");
});
4

2 回答 2

1

试试这个,使用 setInterval() 并计算位置

    var moveAmm = 0;
    var bgAmm = 201;
    var slideInterval = setInterval(function () {
        moveAmm < 480 ? moveAmm += 160 : moveAmm = 0;
        bgAmm == 81 ? bgAmm = 201 : bgAmm -= 40;
        $('#slider-ul').css('top', '-' + moveAmm + "px");
        $('#slider-nav').css('background', 'url(http://dev.learningpeople.co.uk/imgs/entry-it/slider-nav.png) repeat-y 0 -' + bgAmm + 'px');
    }, 3000);

演示

于 2013-09-11T13:16:51.007 回答
1

您可以使用setInterval让函数每隔这么多毫秒运行一次。此功能可以移动到下一张幻灯片。请注意,这会.click稍微影响您的功能,因为它们可能会在间隔自动切换幻灯片的同时被单击。

JSFiddle

var top = -320;
var offset = -121;
var nextSibling;
setInterval(function () {
    autoSlide();
}, 3000);

function autoSlide() {
    if (top == -480) {
        top = 0;
        offset = -201;
        nextSibling = $("#slider-nav li:first");
    } else {
        top -= 160;
        offset += 40;
        nextSibling = $(".selected").next("li");
    }
    document.getElementById("slider-ul").style.top = top + "px";
    document.getElementById("slider-nav").style.background = "url(http://dev.learningpeople.co.uk/imgs/entry-it/slider-nav.png) repeat-y 0 " + offset + "px";
    $("#slider-nav li").removeClass("selected");
    nextSibling.addClass("selected");
}
于 2013-09-11T13:52:30.880 回答