使用javascript更改刷新后的html背景

时间:2012-11-24 14:11:56

标签: javascript html css background-image

我想在每次刷新时更改我的html背景图片。

这就是我在CSS中的内容

html { 
    background-repeat:no-repeat;
    background-position:center center;
    background-attachment:fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

这就是我用javascript(在一个单独的js文件中):

var totalCount = 6;
function ChangeBackground()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.parentNode.background = 'background/test/'+num+'.jpg';

}

我在我的html结尾调用我的函数:

<script type="text/javascript">
ChangeBackground();
</script>

我无法使用我的javascript代码在html标签上添加背景。还有其他办法吗?

我特别想在html标签上使用它,因为我觉得更好:

  

由于CSS3中的background-size属性,我们可以完全通过CSS完成。我们将使用html元素(优于body,因为它始终至少是浏览器窗口的高度)。我们在其上设置了固定且居中的背景,然后使用设置为封面关键字的背景大小调整其大小。

http://css-tricks.com/perfect-full-page-background-image/

2 个答案:

答案 0 :(得分:2)

尝试将background-image样式属性值设置为网址,而不是直接指定链接

ie:使用document.body.parentNode.style.backgroundImage = 'url(background/test/'+num+'.jpg)';代替document.body.parentNode.background = 'background/test/'+num+'.jpg';

JSFiddle:http://jsfiddle.net/HHeKK/

答案 1 :(得分:0)

您无法将背景添加到<html>标记!

以这种方式更改您的代码:

document.body.style.backgroundImage = 'background/test/'+num+'.jpg';