随机背景GIF不起作用

时间:2016-07-19 17:43:07

标签: javascript html css arrays background

我有代码,当身体加载时,它从文件夹中选择一个随机gif并将其用作背景。当加载新页面或同一页面时,它会选择另一个随机gif作为背景。我已经在线查看,即使代码相对相同,它也不会加载新的gif作为背景。这是HTML代码。

<html lang="en">
<head>

    <!-- Random Background Image -->
    <script>
    function newBackground()
    {
        // Set up the image files to be used.
        var theBackgrounds = new Array() // do not change this

        // To add more image files, continue with the pattern below, adding to the array.
        theBackgrounds[0] = 'images/EXTRA/Backgrounds/equalizer.gif'
        theBackgrounds[1] = 'images/EXTRA/Backgrounds/equalizer2.gif'
        theBackgrounds[2] = 'images/EXTRA/Backgrounds/recordSpinning.gif'

        var p = theBackgrounds.length;

        var whichBackground = Math.round(Math.random()*(p-1));


        document.body.style.background = theBackgrounds[whichBackground];
    }
    </script>

  </head>
  <body onLoad="newBackground();">
      *some code*
  </body>
</html>

以下是styles.css中正文的CSS代码。

body{
        background-size:cover;
        background-repeat: repeat-y;
        background-attachment: fixed;
        background-color:#000000;
        color:#FFF;
        font-size:13px;
        font-family: Helvetica, Arial, sans-serif;
        text-align:left;
    }

为什么代码不起作用?

1 个答案:

答案 0 :(得分:1)

因为这不是您使用CSS设置背景图片的方式。你错过了url()部分。

应该是

document.body.style.backgroundImage = "url(" + theBackgrounds[whichBackground] + ")";