[英]Randomize background img with JS
I have working code, that randomly changes background of the body
with my gif's. 我有有效的代码,可以通过gif随机更改
body
背景。
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. 现在,我想将其与另一个HTML元素(例如div之一)一起使用。 Changing
document.body.background
to document.getElementById('id').background
doesn't work. 将
document.body.background
更改为document.getElementById('id').background
无效。 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
: 同样,带有
Math.ceil()
的RNG表示图像基于1
而不基于0
:
1.gif
2.gif
...
11.gif
If this is not the case use Math.floor()
: 如果不是这种情况,请使用
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:
这是一个示例HTML元素:
<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(..)";
document.body.background
主要用于正文背景,但不适用于其他html元素。因此使用了此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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.