Javascript滑块循环
我一直在尝试为html创建一个图像滑块,方法是更改image元素的值,使用循环遍历每个图像,然后返回到原始图像 但是,一旦到达循环的末尾,它就不会继续 以下是我的Js代码:Javascript滑块循环,javascript,html,loops,slider,Javascript,Html,Loops,Slider,我一直在尝试为html创建一个图像滑块,方法是更改image元素的值,使用循环遍历每个图像,然后返回到原始图像 但是,一旦到达循环的末尾,它就不会继续 以下是我的Js代码: window.onload=function(){ 变量x=0 while(x我建议您在这种情况下不要执行while循环。执行时只需调用setTimeout window.onload = function() { /* Element */ var carousel = document.getElem
window.onload=function(){
变量x=0
while(x我建议您在这种情况下不要执行while
循环。执行时只需调用setTimeout
window.onload = function() {
/* Element */
var carousel = document.getElementById('carousel'),
/* Carousel current image */
cimage = 2,
/* Carousel source images */
csources = [
'img/header2.jpg',
'img/header3.jpg',
'img/header.jpg'
];
function changeCarouselImage() {
// Reset the current image if it's ultrapassing the length - 1
if(cimage >= 3) cimage = 0;
// Change the source image
carousel.src = csources[cimage ++];
// Re-call the function after 5s
setTimeout(changeCarouselImage, 5000);
}
setTimeout(changeCarouselImage, 5000);
};
在这种情况下,我建议您不要在
循环时执行。只要在执行时调用setTimeout
window.onload = function() {
/* Element */
var carousel = document.getElementById('carousel'),
/* Carousel current image */
cimage = 2,
/* Carousel source images */
csources = [
'img/header2.jpg',
'img/header3.jpg',
'img/header.jpg'
];
function changeCarouselImage() {
// Reset the current image if it's ultrapassing the length - 1
if(cimage >= 3) cimage = 0;
// Change the source image
carousel.src = csources[cimage ++];
// Re-call the function after 5s
setTimeout(changeCarouselImage, 5000);
}
setTimeout(changeCarouselImage, 5000);
};
最后一个函数不会设置另一个超时,因此动画不会继续。将其分离为单独的函数应有助于:
var carousel = document.getElementById('carousel');
function ani1() {
carousel.src = 'img/header.jpg';
window.setTimeout(ani2, 500);
}
function ani2() {
carousel.src = 'img/header2.jpg';
window.setTimeout(ani3, 500);
}
function ani3() {
carousel.src = 'img/header3.jpg';
window.setTimeout(ani1, 500);
}
window.onload = ani1;
最后一个函数不会设置另一个超时,因此动画不会继续。将其分离为单独的函数应有助于:
var carousel = document.getElementById('carousel');
function ani1() {
carousel.src = 'img/header.jpg';
window.setTimeout(ani2, 500);
}
function ani2() {
carousel.src = 'img/header2.jpg';
window.setTimeout(ani3, 500);
}
function ani3() {
carousel.src = 'img/header3.jpg';
window.setTimeout(ani1, 500);
}
window.onload = ani1;
你的x增量行缺少一个分号。这是不需要的。我不久前做了类似的事情。也许我的提琴会给你一些指导:你的x增量行缺少一个分号。这是不需要的。我不久前做了类似的事情。也许我的提琴会给你一些指导:谢谢,这很有效,但不重复再次浏览图片?抱歉,我是javascript新手。谢谢,这很有效,但是不会再次浏览图片?抱歉,我是javascript新手。