我的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");
});
答案 0 :(得分: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);
答案 1 :(得分:1)
您可以使用setInterval
使函数每隔很多毫秒运行一次。此功能可以移动到下一张幻灯片。请注意,这会稍微影响您的.click
功能,因为可能会在间隔自动切换幻灯片的同时点击它们。
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");
}