简体   繁体   中英

Randomize background img with JS

I have working code, that randomly changes background of the body with my gif's.

var totalCount = 11;
function ChangeIt() {
  var num = Math.ceil( Math.random() * totalCount );
  document.body.background = '/static/img/'+num+'.gif';
  document.body.style.backgroundRepeat = "repeat";
  }
window.onload = ChangeIt;

Now I want to use it with another HTML element, one of the div's, for example. Changing document.body.background to document.getElementById('id').background doesn't work. How should I change the code?

Have you tried this?

document.getElementById('id').style.backgroundImage = "url('/static/img/" + num + ".gif')";

Also, the RNG with Math.ceil() means that images are based on 1 not on 0 :

1.gif
2.gif
...
11.gif

If this is not the case use Math.floor() :

0.gif
1.gif
...
10.gif

Depending on what the element is, you may need to set its dimensions (width and height). This is an example HTML element:

<div id="imagediv" style="width: 320px; height: 640px; background-repeat: repeat;"></div>

This the resulting code:

var totalCount = 11;

window.onload = function () {
  var num, node;

  num = Math.ceil(Math.random() * totalCount);
  node = document.getElementById("imagediv");

  node.style.backgroundImage = "url('/static/img/" + num + ".gif')";
};

这应该是正确的语法:

document.getElementById('id').style.backgroundImage = "url('img_tree.png')";

document.body.background mostly worked for body background but not other html elements.So used this document.getElementById('id').style.backgroundImage = "url(..)";

var totalCount = 11;
function ChangeIt() {
  var divs =document.getElementById('id');
  var num = Math.ceil( Math.random() * totalCount );
  divs.style.backgroundImage = 'url(/static/img/'+num+'.gif)';
  divs.style.backgroundRepeat = "repeat";
  divs.style.height = "300px"; //testing
  }
window.onload = ChangeIt;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM