制造阵列您要使用的图像:
var images = [
"https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx",
"https://www.petfinder.com/wp-content/uploads/2013/09/cat-black-superstitious-fcs-cat-myths-162286659.jpg",
"https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg"
]
我们检索其在div
您想要更改的背景:
var imageHead = document.getElementById("image-head");
您现在可以使用使用setInterval
更改背景图片的URL每秒(你想或任何间隔):
var i = 0;
setInterval(function() {
imageHead.style.backgroundImage = "url(" + images[i] + ")";
i = i + 1;
if (i == images.length) {
i = 0;
}
}, 1000);
这里是一个活生生的例子:https://jsfiddle.net/vvwcfkfr/1/
使用功能规划,ES6和递归的一些改进:
const cats = [
"https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx",
"https://www.petfinder.com/wp-content/uploads/2013/09/cat-black-superstitious-fcs-cat-myths-162286659.jpg",
"https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg"
]
const node = document.getElementById("image-head");
const cycleImages = (images, container, step) => {
images.forEach((image, index) => (
setTimeout(() => {
container.style.backgroundImage = `url(${image})`
}, step * (index + 1))
))
setTimeout(() => cycleImages(images, container, step), step * images.length)
}
cycleImages(cats, node, 1000)
https://jsfiddle.net/du2parwq/
你的意思是像[引导旋转木马(http://getbootstrap.com/您的问题的JavaScript /#旋转木马)? – Roberto
[使用jquery每隔10秒改变div的淡入淡出效果的背景图像]可能的重复(http://stackoverflow.com/questions/5507518/change-background-image-of-a-div-with-fade-效果每10秒与jquery) – Rob