随机背景更改仅适用于Firefox?

时间:2013-07-06 12:17:23

标签: javascript html cross-browser background-image

我的代码似乎在Firefox上运行完美。但是当我想在IE或Chrome上运行时,我的背景似乎是空白的。我的代码有问题吗?或者我在测试它的浏览器上不支持它?

<html>
<head>
    <script>
    window.onload = function () {
     var imgs = [
        'images/1.jpg',
        'images/2.jpg',
        'images/3.jpg',
        'images/4.jpg',
        'images/5.jpg',
        'images/6.jpg'
     ];
     document.body.style = 'background: url(' + imgs[Math.round(Math.random() * imgs.length)] + ') no-repeat ; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;';
    }
    </script>
    <link rel="stylesheet" type="text/css" href="styles.css" />
</head>

<body>
    <?php include ("header.php"); ?>
    <div align="center" >
        <?php include ("main.php"); ?>
        <?php include ("footer.php"); ?>
    </div>
</body>

3 个答案:

答案 0 :(得分:3)

你的语法错了。它应该是:

var body = document.body;
body.style.background = 'url(' + imgs[Math.round(Math.random() * imgs.length)] + ') no-repeat';
body.style.webkitBackgroundSize = 'cover';

http://jsfiddle.net/CGsxB/

一次性设置一组属性作为字符串可能在Firefox中有效,但一般情况下应单独设置各个样式属性。

答案 1 :(得分:0)

试试这个

<script>
function my_function() {
 var imgs = [
    'images/1.jpg',
    'images/2.jpg',
    'images/3.jpg',
    'images/4.jpg',
    'images/5.jpg',
    'images/6.jpg' ];
 document.body.style = 'background: url(' + imgs[Math.round(Math.random() * imgs.length)] + ') no-repeat ; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;';

 //also you can try like
    document.getElementByTagName('body').style = 'background: url(' + imgs[Math.round(Math.random() * imgs.length)] + ') no-repeat ; 
    -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;';
}
  my_function();   //Just call this 
</script>

它会在每个页面加载时调用my_function()。因为window.onload 可能不支持所有浏览器及其版本

答案 2 :(得分:0)

使用style.cssText不是更好吗?

document.body.style.cssText = 'background: url(' + imgs[Math.floor(Math.random() * imgs.length)] + ') no-repeat ; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;';

此外,似乎Math.round(Math.random() * imgs.length)有时会产生imgs.length作为结果并超出数组边界,所以我建议改为Math.floor