Using js operation CSS to implement js to change the background image example
- 2020-03-30 02:21:42
- OfStack
1. Use JS to define an array of images that you want to display randomly
ar imgArr=["//www.jb51.net/logo_cn.png",
"//www.jb51.net/baidu_sylogo1.gif",
"//www.jb51.net/news/uploadImg/20120111/20120111081906_79.jpg",
"//www.jb51.net/news/uploadImg/20120111/20120111081906_76.jpg"];
Please replace the above picture with your own.
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>