我试图从头开始重新创建碎砖游戏,但我似乎无法移动这个元素。我打开谷歌chrome开发工具,它告诉我
Uncaught TypeError: Cannot read properties of null (reading 'style')
我已经尝试了我能想到的一切,但似乎都不起作用,帮助会很好,谢谢。
let userObject = document.querySelector('#user') ;
window.addEventListener('load', () =>{
document.getElementById('user').style.position = 'absolute' ;
userObject.style.position = "absolute"; });
window.addEventListener('keyup', (event) => {
switch (event.key) {
case 'ArrowLeft':
userObject.style.left = parseInt(userObject.style.left) - 5 + 'px';
break;
case 'ArrowRight':
userObject.style.left = parseInt(userObject.style.left) + 5 + 'px';
break;
case 'ArrowUp':
userObject.style.top = parseInt(userObject.style.top) - 5 + 'px';
break;
case 'ArrowDown':
userObject.style.top = parseInt(userObject.style.top) + 5 + 'px';
break;
default:
alert("Only Arrow Keys Are Allowed!");
} });
#userbox {
display : flex ;
align-items: center;
justify-content: center;
height: 100vh;
width : 100% ;
}
#user {
display : flex ;
width: 70px ;
height : 10px ;
background-color : black ;
}
<div id = "userbox"><span id= "user"> </span></div>
任何帮助都会很棒。谢谢大家。
我认为脚本在html渲染之前运行所以它首先找到user元素,所以userObject将为null。
解决方案是->在窗口onload事件侦听器中声明userObject或->在导入脚本时使用async/defere关键字