admin管理员组文章数量:1293239
I have a "container" DIV that scales to fit the window 100% and I would like to load a random image into the DIV. I have a working script that works for the html background, but I can't get it to work on a DIV instead.
Anyn suggestions?
Here is the original script:
<script type="text/javascript">
var imgCount = 3;
var dir = 'images/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "bg-01.jpg",
images[2] = "bg-02.jpg",
images[3] = "bg-03.jpg",
document.body.style.backgroundImage = "url(" + dir + images[randomCount] + ")"; </script>
I have a "container" DIV that scales to fit the window 100% and I would like to load a random image into the DIV. I have a working script that works for the html background, but I can't get it to work on a DIV instead.
Anyn suggestions?
Here is the original script:
<script type="text/javascript">
var imgCount = 3;
var dir = 'images/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "bg-01.jpg",
images[2] = "bg-02.jpg",
images[3] = "bg-03.jpg",
document.body.style.backgroundImage = "url(" + dir + images[randomCount] + ")"; </script>
Share
edited Jan 30, 2013 at 11:06
svz
4,58811 gold badges44 silver badges66 bronze badges
asked Jan 30, 2013 at 11:05
Craig Jonathan KristensenCraig Jonathan Kristensen
7373 gold badges13 silver badges22 bronze badges
1
- And what is a problem with div? Show your code where you are trying to set a background for a div, not for body. – Viktor S. Commented Jan 30, 2013 at 11:09
2 Answers
Reset to default 5There should be no problem with that. Just find that div, for instance with document.getElementById() and apply a background image to it:
<div id="divID"></div>
<script type="text/javascript">
var imgCount = 3;
var dir = 'images/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "bg-01.jpg",
images[2] = "bg-02.jpg",
images[3] = "bg-03.jpg",
document.getElementById("divID").style.backgroundImage = "url(" + dir + images[randomCount] + ")";
</script>
But note that above script block must go AFTER a div you need to update.
Otherwise, at the moment of script execution div will be not available in DOM and document.getElementById
will find nothing.
document.body.style.backgroundImage
sets the background to <body>
You can easily force it to do it for your selected div by doing:
document.getElementById('divID').style.backgroundImage = "url(" + dir + images[randomCount] + ")";
本文标签: javascriptRandom imagebackground in divStack Overflow
版权声明:本文标题:javascript - Random image-background in div - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741571586a2386040.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论