2016-05-15 56 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