我尝试使用background-image: url
<div>
setInterval
setInterval.
现在,背景图像仅在停止前切换一次。我应该提到我使用Jinja和一些JavaScript,但这两种语言在语法上包含相似之处。
$(function() {
// Array of images
var carouselImages = [
// Returns a list containing a progression of integers
// Similar to iterating over an array
{% for n in range(1, coursePhotos) %}
"{{ COPY.content.cdn_url }}/courses/{{course.slug}}/{{course.slug}}-{{n}}.jpg",
{% endfor %}
];
// The div of the background I want to change
var carousel = $(".course__images");
// Change the background image every four seconds
var changeBackgroundImage = setInterval(function(){
// Returns a list containing a progression of integers
// Similar to iterating over an array
{% for n in range(1, coursePhotos) %}
carousel.css("background-image", "url({{ COPY.content.cdn_url }}/courses/{{course.slug}}/{{course.slug}}-{{n}}.jpg");
{% endfor %}
}, 4000);
});
答案 0 :(得分:2)
实施例
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);
JSFiddle演示:https://jsfiddle.net/3wayry32/1/