製造陣列您要使用的圖像:
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