[英]Image Slider- Javascript
有人知道為什么這段代碼沒有通過1.fw.png到5.fw.png更改我的圖像嗎?
HTML
<div id="slideshow">
<img id="slider" src="1.fw.png">
</div>
JavaScript的
function timer(x){
var timer = setTimeout(function () {switchPic(x);}, 4000);
}
function switchPic(x){
x += 1;
document.getElementById('slider').src = x + ".fw.png";
}
$(document).ready()(function(){
document.getElementById('slider').src = x;
timer(x);
});
帶有過渡的Image Changer將是一個好處,但是僅更改圖像是基本要求。
x
是局部變量(參數),因此增量更改不會超過switchPic
函數。 如果有一個全局x
那么它就會被遮蓋; 否則, timer(x)
將導致ReferenceError-確保確實描述什么 “無效”以及如何得知。
我可能會這樣寫:
jQuery(function ($) {
var t = -1; // initial value peicked so x is 1 at first interval
function switchIt () {
t++; // change variable caught in closure
var x = (t % 5) + 1; // loops through values in 1..5
$('#slider').attr("src", x + ".fw.png");
}
// set initial image right away
switchIt();
// switch image every 4 seconds, forever
setInterval(switchIt, 4000);
});
謝謝user2864740,我用您的信息重新編寫了代碼,它現在也以正確的數字循環。
$(document).ready(function(){
setInterval(function(){
z = document.getElementById('slider').src;
y = z.indexOf(".fw.png");
y = z.slice(y - 1, -7);
x = parseInt(y);
y = (x % 5) + 1;
document.getElementById('slider').src = "/Images/Index/Slider/" + y + ".fw.png";
},4000);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.