Javascript随机图像丢失样式

时间:2017-02-22 05:02:40

标签: javascript html css

尝试为我的Jumbotron设置随机背景图像。这是我到目前为止所拥有的。

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写这个?

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;