繁体   English   中英

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

[英]How do I change the background image every X seconds?

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

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

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

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

谢谢!

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

使用您要使用的图像创建一个数组

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://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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM