【发布时间】:2016-08-28 11:40:35
【问题描述】:
我使用 nginx 和 chrome 作为浏览器。我只是想改变一个div的背景颜色。并且孤立的 JS 在小提琴中工作。但是完整的标记不起作用。
我在横幅 div 的浏览器控制台中不断收到“TypeError: Cannot read property 'style' of null”。
<!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>
【问题讨论】:
-
工作正常...jsfiddle.net/538otjwe
-
因为您提供的是函数调用,而不是 onload 事件处理程序的函数引用。使用
document.onload = f。 -
@SpencerWieczorek 这停止了错误,但 JS 也不起作用。
-
@user193661 使用
window.onload = f,更受支持。
标签: javascript html