div中的随机图像背景 [英] Random image-background in div

查看:85
本文介绍了div中的随机图像背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个容器DIV可以缩放以适应100%的窗口,我想将随机图像加载到DIV中。
我有一个适用于html背景的工作脚本,但我无法让它在DIV上工作。

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建议?

这是原始脚本:

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


推荐答案

应该没有问题。只需找到div,例如使用document.getElementById()并应用背景图像:

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

但请注意,上面的脚本块必须在你需要更新的div之后。
否则,在脚本执行时,div将无法在DOM中使用, document.getElementById 将找不到任何内容。

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中的随机图像背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆