JS operation CSS random change web page background implementation ideas

  • 2020-03-30 02:21:08
  • OfStack

Today, a friend asked me on weibo whether I could use JS and CSS to randomly generate a background image every time the page refreshes. Of course, my answer was ok. Specifically, it can be done as follows:
1. Use JS to define an array of images that you want to display randomly
 
var imgArr=["http://www.google.com.hk/intl/zh-CN/images/logo_cn.png", 
"http://www.baidu.com/img/baidu_sylogo1.gif", 
"http://www.open-open.com/news/uploadImg/20120111/20120111081906_79.jpg", 
"http://www.open-open.com/news/uploadImg/20120111/20120111081906_76.jpg" 
]; 

Here I found 4 pictures at random and have a closer look.
2. Generate a random number with JS, starting from 0 and ending at imgarr.leng-1
 
var index =parseInt(Math.random()*(imgArr.length-1)); 

So we get the current randomly generated image
 
var currentImage=imgArr[index]; 

3. Since a background picture is generated randomly, use JS to take this picture as the background picture.
 
document.getElementById("BackgroundArea").style.backgroundImage="url("+currentImage+")"; 

Since this is a demo, I've defined a div on the page with an id of BackgroundArea and a random background for that div.
 
<div id="BackgroundArea"> 
</div> 

Related articles: