javascript div中的随机图像背景
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14602482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random image-background in div
提问by Craig Jonathan Kristensen
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.
我有一个“容器”DIV,可缩放以 100% 适合窗口,我想将随机图像加载到 DIV 中。我有一个适用于 html 背景的工作脚本,但我无法让它在 DIV 上工作。
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>
回答by Viktor S.
There should be no problem with that. Just find that div, for instance with document.getElementById() and apply a background image to it:
应该没有问题。只需找到该 div,例如使用 document.getElementById() 并为其应用背景图像:
<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.
但请注意,上面的脚本块必须在您需要更新的 div 之后。否则,在脚本执行的那一刻, div 在 DOMdocument.getElementById
中将不可用并且什么也找不到。
回答by Andy
document.body.style.backgroundImage
sets the background to <body>
document.body.style.backgroundImage
将背景设置为 <body>
You can easily force it to do it for your selected div by doing:
您可以通过执行以下操作轻松强制它为您选择的 div 执行此操作:
document.getElementById('divID').style.backgroundImage = "url(" + dir + images[randomCount] + ")";