我有3个文件
文件 1:index.html
<!DOCTYPE html>
<html>
<head>
<LINK href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="bounce.js"></script>
<title>Bouncing ball</title>
</head>
<body>
<div id='ball'></div>
</body>
</html>
文件 2:bounce.js
var ball = document.getElementById("ball");
var nx = 0;
var ny = 0;
setInterval(loop, 1000 / 30);
function loop() {
nx++;
ny++;
ball.style.left = nx;
ball.style.top = ny;
}
文件 3:样式.css
#ball {
position: absolute;
border-radius: 50px;
width: 50px;
height: 50px;
background: black;
}
我在 html 文件中加载 .css 和 .js。 现在我正试图让 te div “球”,我想用它做点什么。在这种情况下,我想让它再次弹回浏览器的边界。但关键是,我遇到了错误。
未捕获的类型错误:无法读取 null 的属性“样式”
bonce.js 获取不到elment 球。为什么不?我做错了什么?
最佳答案
您正试图在元素加载到 DOM 之前获取该元素。这样做:
<!DOCTYPE html>
<html>
<head>
<LINK href="style.css" rel="stylesheet" type="text/css">
<title>Bouncing ball</title>
</head>
<body>
<div id='ball'></div>
<script type="text/javascript" src="bounce.js"></script>
</body>
</html>
在底部包含所有 JavaScript 是一个很好的做法,这样它就不会在下载时阻塞页面。它将确保您不会遇到任何此类错误。
关于javascript - var ball = document.getElementById ("ball");返回空对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14223878/