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

Bre*_*aig 8 html javascript css jquery 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;
}
Run Code Online (Sandbox Code Playgroud)

基本上,我想要做的是每X秒改变它的背景图像urldiv点数,但我不确定如何做到这一点.

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

<div class="image-head">
  <div class="centering-hack">
    <h1>Something HTML</h1>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

编辑:如果JS库让任何事情变得更容易,我正在使用Bootstrap 3

Fau*_* NA 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"
]
Run Code Online (Sandbox Code Playgroud)

我们检索div您要更改的背景:

var imageHead = document.getElementById("image-head");
Run Code Online (Sandbox Code Playgroud)

您现在可以使用setInterval每秒更改背景图像URL(或您想要的任何间隔):

var i = 0;
setInterval(function() {
      imageHead.style.backgroundImage = "url(" + images[i] + ")";
      i = i + 1;
      if (i == images.length) {
        i =  0;
      }
}, 1000);
Run Code Online (Sandbox Code Playgroud)

这是一个实例: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)
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/du2parwq/