选择随机背景 - HTML / CSS

时间:2014-11-19 21:37:38

标签: html css image random background

在这里填写HTML / CSS / JS noob,但我无法找到有关此内容的任何信息:

我想实现随机背景'在我的网站上,所以每当有人刷新页面时,都会有新的背景。遗憾的是我不能使用PHP,我发现这个:http://css-tricks.com/snippets/php/randomize-background-image/虽然对学习很有用,但我实际上并没有使用它。

我目前的代码:

.mainview {
    background-image: url(images/bg-1.png);
    height: 600px;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: bottom center;
    background-attachment: fixed;
    position: relative;
    top: 12px
}

我希望它从我拥有的三个列表中选择一个随机的(bg-1,bg-2,bg-3),而不是将url设置为一个图像。我该怎么做?

有点长,对不起! 提前致谢

1 个答案:

答案 0 :(得分:5)

创建一个图像数组,使用Math.random()获取随机索引并使用该索引获取随机图像。

<script type="text/javascript">

  var images = ['image-1.jpg', 'image-2.jpg', 'image-3.jpg', 'image-4.jpg'];
  document.getElementsByClassName('mainview')[0].style.backgroundImage = 'url(' + images[Math.floor(Math.random() * images.length)] + ')';

</script>
相关问题