更改html标签本身的背景

时间:2016-04-15 19:47:10

标签: javascript css

如何更改此标记的背景?

HTML

<!DOCTYPE html>
<html class="full" lang="en">

JS

    window.onload = function () {
       var fileNumber = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
       var imgContainer = document.getElementsByClassName("full");

   // It does not work...    
  imgContainer.style.background = "url('../images/' + fileNumber + '.jpg') no-repeat center center fixed";
    }

CSS

.full {
    background: url('../images/5.jpg') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
}

2 个答案:

答案 0 :(得分:2)

document.getElementsByClassName返回一个数组,因此您需要使用:

imgContainer[0].style.background = "url('../images/" + fileNumber + ".jpg') no-repeat center center fixed";

答案 1 :(得分:2)

您当前正在使用可以返回元素数组的document.getElementsByClassName()函数,因此您需要指定要更新的确切索引:

imgContainer[0].style.background = 'url("../images/' + fileNumber + '.jpg") no-repeat center center fixed';

或者由于您直接定位html元素,因此您可以使用document.documentElement指向它:

document.documentElement.style.background = 'url("../images/' + fileNumber + '.jpg") no-repeat center center fixed';