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=["//",

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.


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">

Related articles: