无法读取属性样式错误

时间:2016-08-28 03:14:57

标签: javascript html

我使用nginx和chrome作为浏览器。我只是想改变div的背景颜色。孤立的JS在小提琴中起作用。但是完整的标记不起作用。

我一直在" TypeError:无法读取属性' style' of null"在横幅div的浏览器控制台中。

<!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8"> -->
<title>ZZZ lin!</title>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<!-- <link rel="stylesheet" href="/static/global.css" type="text/css"> -->
<style type="text/css">
#banner {
        display:inline;
        position:absolute;
        top:0px;
        left:0px;
        height:40px;
        width:100%;
        background-color:green;
}
</style>
<script type="text/javascript">
var banner_colors = ['#d99b00', '#7f5b00', '#332d0d', '#fffb00', '#888c69', '#9bbf30', '#dbf2b6', '#1f5900', '#59b376', '#00e667', '#004d2d', '#80ffec', '#739993', '#00cbe6', '#263233', '#0095f2', '#1d5273', '#b6dbf2', '#3354cc', '#162559', '#8f93bf', '#2a00e6', '#474359', '#390080', '#5b3973', '#250033', '#b539e6', '#c499cc', '#800071', '#660031', '#d93685', '#8c4668', '#cc002c', '#d9a3ae', '#660009', '#ff808a', '#403031'];
var i = 0, howManyTimes = banner_colors.length;
function f() {
    document.getElementById('banner').style.backgroundColor = banner_colors[i];
    i++;
    if( i < howManyTimes ){
        setTimeout( f, 1000 );
    }
}
document.onload = f();

</script>
</head>
<body>
    <div id="banner">
    </div>
    <div id="main-content">
        <p>Main page content goes here</p>
        <p>Main page content goes here</p>
        <p>Main page content goes here</p>
        <p>Main page content goes here</p>
        <p>Main page content goes here</p>
    </div>
<h1>Hello from Flask!</h1>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

在页面加载后使用window.addEventListener("load", f)运行它(其中f是函数内包含的<script>标记的内容。)