Max*_*son 0 html css random background image
在这里完成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
}
Run Code Online (Sandbox Code Playgroud)
而不是将url设置为一个图像,我希望它从我拥有的三个列表中选择一个随机的(bg-1,bg-2,bg-3).我该怎么做?
有点长,对不起!提前致谢
创建一个图像数组,用于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>
Run Code Online (Sandbox Code Playgroud)