0

私のコードは 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>

4

3 に答える 3

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 で機能する可能性がありますが、一般的には個々のスタイル プロパティを個別に設定する必要があります。

于 2013-07-06T12:25:05.803 に答える
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代わりに提案します。

于 2013-07-06T12:39:40.703 に答える