如何更改此标记的背景?
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;
}
答案 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';