如何使用localhost在页面刷新时交换背景图像?

时间:2011-04-03 20:01:10

标签: javascript image random background

我需要能够在页面刷新时交换背景图像。我试图用javascript做这个,我正在引用我为页面正文设置的id。这是我到目前为止所提出的,似乎没有起作用:

<script type="text/javascript">
    window.onload = choosePic;

    function choosePic() {
    var myPix = new Array("/CoVPrototype/images/Homepage/skyline_bkgd_blue_fixed.jpg", "/CoVPrototype/images/AboutPage/about_bkgd.jpg", "/CoVPrototype/images/GovernmentPage/gov_bkgd.jpg", "/CoVPrototype/images/newsPage/news_bkgd.jpg", "/CoVPrototype/images/parkPage/park_bkgd.jpg", "/CoVPrototype/images/propertyPage/property_bkgd.jpg", "/CoVPrototype/images/enviroPage/enviro_bkgd.jpg", "/CoVPrototype/images/transportPage/transport_bkgd.jpg", "/CoVPrototype/images/businessPage/business_bkgd.jpg");
    var randomNum = Math.floor(Math.random() * myPix.length);
    document.getElementById("home_style").src = myPix[randomNum];
    }

我在HTML中引用的标记是这样设置的(请注意,所有其他HTML标记都已应用...为了简洁起见,此处未显示):

<body id="home_style">
</body> 

最后,我的CSS看起来像这样:

body {
        margin:0;
        padding:0;
        font-size:62.5%;
        font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
}
    body#home_style {
            background:no-repeat bottom left fixed;
            width:100%;
    }

这应该有用吗?我究竟做错了什么?!我希望有人可以帮忙!!

1 个答案:

答案 0 :(得分:0)

这应该有效:

document.getElementById("home_style").style.backgroundImage = "url(" + myPix[randomNum] + ")";