2017-02-22 79 views
8

試圖爲我的Jumbotron設置隨機背景圖像。這是我到目前爲止。Javascript隨機圖像丟失造型

function randomImage() { 
    var images = [ 
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTZwkTaJg28-Bxidgfm6FbHyEZ8D5ya1hGMroF05htuwvQqJsY9sQ", 
    "http://www.shunvmall.com/data/out/193/47120931-random-image.png", 
    "https://s-media-cache-ak0.pinimg.com/originals/2b/05/14/2b05140a776f25a8047c88fbe2bcbdb9.jpg" 
    ]; 
    var imgAmount = images.length 
    console.log(imgAmount); 
    var x = Math.floor(imgAmount * Math.random()) 
    console.log(x); 
    document.getElementsByClassName('jumbotron')[0].style.background = "url(" + images[x] + ") no-repeat center center fixed"; 
} 
window.onload = randomImage; 

但是這個工程頁面上加載在我的CSS表中定義的樣式似乎被覆蓋?

.container .jumbotron { 
    background: url(/static/images/banner-1.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover; 
    -moz-background-size: cover; 
    -o-background-size: cover; 
    background-size: cover; 
    margin-bottom: 0px; 
    border-radius: 0px; 
} 

有沒有一種方式來加載這些隨機圖像,並保持其他風格已經定義?

此外,另一個快速問題..我只使用getElementsByClassName [0],因爲我無法使querySelector工作。我怎麼會用querySelector寫這個?

+0

你可以發佈一個可行的代碼片段,與HTML? –

+1

那麼,對於查詢選擇器來說,它看起來像這樣:document.querySelector('。jumbotron') – user218046

+0

@ user218046我要回復並說這是我嘗試的第一件事!但現在起作用了,一定是錯字。多麼尷尬..謝謝! – Jesse

回答

4

使用JavaScript更改style.background屬性重置所有背景屬性(包括background-size以及)。您可能只想使用JavaScript來更改backgroundImage屬性,以保持CSS中定義的其他背景樣式。

document.querySelector('.jumbotron').style.backgroundImage = 'url(...)'; 

function randomImage() { 
 
    var images = [ 
 
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTZwkTaJg28-Bxidgfm6FbHyEZ8D5ya1hGMroF05htuwvQqJsY9sQ", 
 
    "http://www.shunvmall.com/data/out/193/47120931-random-image.png", 
 
    "https://s-media-cache-ak0.pinimg.com/originals/2b/05/14/2b05140a776f25a8047c88fbe2bcbdb9.jpg" 
 
    ]; 
 
    var imgAmount = images.length; 
 
    var x = Math.floor(imgAmount * Math.random()); 
 
    document.querySelector('.jumbotron').style.backgroundImage = "url(" + images[x] + ")"; 
 
} 
 

 
window.onload = randomImage;
.container .jumbotron { 
 
    background: url(https://placehold.it/300x200) no-repeat center center fixed; 
 
    -webkit-background-size: cover; 
 
    -moz-background-size: cover; 
 
    -o-background-size: cover; 
 
    background-size: cover; 
 

 
    margin-bottom: 0px; 
 
    border-radius: 0px; 
 
    height: 200px; 
 
    border: 6px #000 solid; 
 
}
<div class="container"> 
 
    <div class="jumbotron"> 
 
    </div> 
 
</div>

+0

太棒了!將.style.background更改爲.style.backgroundImage完美。誰知道這麼少會導致這樣的悲傷。謝謝! – Jesse