我正在尝试使对象在屏幕上自动移动。 html
<body>
<h1>Hallo</h1>
<div id='bird'></div>
</body>
main.js
let elemBird = document.getElementById('movingBird');
let birdSpeed = 2;
let birdisAlive = true;
let pos = {
x: -150,
y: Math.floor(Math.random() * window.innerHeight),
endX: window.innerWidth,
endY: window.innerHeight,
};
在下部创建一个具有ID和Img-Tag的Div-Container,在其上...
function createBird() {
const bird = document.createElement('div');
bird.className = 'animation';
bird.id = 'movingBird';
const birdImg = document.createElement('img');
birdImg.src = './assets/Koli.jpeg';
birdImg.className = 'bird-style';
bird.appendChild(birdImg);
document.getElementById('bird').appendChild(bird);
}
function movingDown() {
pos.x += birdSpeed + (Math.random() * 5);
pos.y += birdSpeed + (Math.random() * 15);
}
...然后应使用moveBird()函数移动
function moveBird() {
let id;
if (pos.x <= pos.endX) {
if (birdisAlive) {
pos.x += birdSpeed;
} else if (pos.y <= pos.endY) {
movingDown();
}
elemBird.style.transform = `translate(${pos.x}px, ${pos.y}px)`;
id = requestAnimationFrame(moveBird);
} else {
cancelAnimationFrame(id);
}
}
createBird();
moveBird();
为什么会出现错误?未捕获的TypeError:无法读取null的属性“样式”
(我具有不带pos-object的相同设置,并且可以正常工作。但我的尝试是让多个对象同时移动。)