簡體   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