如何每隔X秒更改背景图像?

时间:2016-05-15 19:28:36

标签: javascript jquery html css twitter-bootstrap-3

我有div填充整个页面(投资组合样式)。 div具有以下风格:

.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秒更改url为其背景图像指向的div,但我不确定如何执行此操作。< / p>

我的标记目前看起来像这样:

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

这里最简单/最好的解决方案是什么?

谢谢!

编辑:如果JS库更容易使用Bootstrap 3

2 个答案:

答案 0 :(得分:8)

使用您要使用的图片制作数组

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 每秒更改背景图片网址(或您想要的任何时间间隔):

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 :(得分:1)

如果我对你的问题感到不满,那你就想要捣蛋 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插件或boostrap

的一些jumbutron
相关问题