2016-05-15 60 views
7

我有一個div填充整個頁面(組合風格)。該div有這種風格:如何每隔X秒更改背景圖片?

.image-head { 
    background: url('http://placehold.it/1920x1080') no-repeat top center fixed; 
    background-size: cover; 
    height: 100%; 
    width: 100%; 
    margin: 0; 
    padding: 0; 
    color: black; 
    text-align: center; 
} 

基本上,我想要做的是每隔X秒改變urldiv點爲它的背景圖片,但我對如何做到這一點不確定。

我的標記目前看起來是這樣的:

<div class="image-head"> 
    <div class="centering-hack"> 
    <h1>Something HTML</h1> 
    </div> 
</div> 

這裏有什麼簡單/最好的解決辦法?

謝謝!

編輯:我使用的是引導3,如果JS庫使事情更容易

+0

你的意思是像[引導旋轉木馬(http://getbootstrap.com/您的問題的JavaScript /#旋轉木馬)? – Roberto

+0

[使用jquery每隔10秒改變div的淡入淡出效果的背景圖像]可能的重複(http://stackoverflow.com/questions/5507518/change-background-image-of-a-div-with-fade-效果每10秒與jquery) – Rob

回答

9

製造陣列您要使用的圖像:

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/

+1

謝謝!這很好用! –

+0

很高興幫助。下面的答案腳本也適用。 –

1

如果我corect underestand你想somthink喜歡 http://codepen.io/dodekx/pen/BKEbPK?editors=1111

var url = ['http://lorempixel.com/400/200/sports/' , 
     'http://lorempixel.com/400/200/city/']; 
curentImageIndex = 0; 
setInterval(function(){ 
console.log(url[curentImageIndex]) 
var p = $('.image-head'); 
    p.css("background","url("+url[curentImageIndex++] + ")"); 
    if(curentImageIndex>= url.length){curentImageIndex = 0} 
}, 1000); 

當然,最好的解決辦法從jQuery插件或自舉一些jumbutron