Javascript 使用setInterval从阵列更改背景图像,但仅更改两次 客观的
我正在尝试根据使用Javascript 使用setInterval从阵列更改背景图像,但仅更改两次 客观的,javascript,jquery,loops,jinja2,setinterval,Javascript,Jquery,Loops,Jinja2,Setinterval,我正在尝试根据使用setInterval的数组中的图像,每四秒钟更改的背景图像:url 阵列中最多可以有四个图像 我遇到的问题是,我需要在数组上循环两次,然后在停止setInterval之前返回数组中的第一个图像。 我在哪里 现在,背景图像在停止之前只切换一次。我应该提到的是,我正在将Jinja与一些JavaScript一起使用,但这两种语言在语法上有相似之处 scripts.js 范例 var images = [ 'https://placeholdit.imgix.net/~tex
setInterval
的数组中的图像,每四秒钟更改
的背景图像:url
- 阵列中最多可以有四个图像
- 我遇到的问题是,我需要在数组上循环两次,然后在停止
setInterval之前返回数组中的第一个图像。
var images = [
'https://placeholdit.imgix.net/~text?txtsize=33&txt=one&w=100&h=100',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=two&w=100&h=100',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=three&w=100&h=100',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=four&w=100&h=100'
];
var img = document.querySelector('#image');
var index = 0;
var iterations = 0;
var updateImage = function() {
/* reset index to zero if current index is greater than number of images.
* increment iterations variable since it means we've done one whole loop.
*/
if (index >= images.length) {
index = 0;
iterations++;
}
// set the background image
img.style.backgroundImage = 'url(' + images[index] + ')';
/* clear interval (stop timer) when we've reached
* the number of iterations allowed.
*/
if (iterations >= 2) {
clearInterval(interval);
} else {
/* increment current index in order to get next image
* when this function gets called again.
*/
index++;
}
}
// update first image
updateImage();
// initiate timer
var interval = setInterval(updateImage, 4000);
jsiddle演示:示例
var images = [
'https://placeholdit.imgix.net/~text?txtsize=33&txt=one&w=100&h=100',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=two&w=100&h=100',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=three&w=100&h=100',
'https://placeholdit.imgix.net/~text?txtsize=33&txt=four&w=100&h=100'
];
var img = document.querySelector('#image');
var index = 0;
var iterations = 0;
var updateImage = function() {
/* reset index to zero if current index is greater than number of images.
* increment iterations variable since it means we've done one whole loop.
*/
if (index >= images.length) {
index = 0;
iterations++;
}
// set the background image
img.style.backgroundImage = 'url(' + images[index] + ')';
/* clear interval (stop timer) when we've reached
* the number of iterations allowed.
*/
if (iterations >= 2) {
clearInterval(interval);
} else {
/* increment current index in order to get next image
* when this function gets called again.
*/
index++;
}
}
// update first image
updateImage();
// initiate timer
var interval = setInterval(updateImage, 4000);
jsiddle演示:看起来很稳定。我希望您能更详细地描述一下
updateImage
中发生的事情。添加了一些注释@AndrewNguyenLooks solid。我希望您能更详细地描述一下updateImage
中发生的事情。添加了一些评论@AndrewNguyen