gpt4 book ai didi

通过 Id 移动图像的 JavaScript 简单错误

转载 作者:行者123 更新时间:2023-11-30 06:26:00 24 4
gpt4 key购买 nike

在下面的代码中,我创建了一个 ID 为“devildead”的新图像,在我尝试使用它的 ID 移动该图像后,出现了这个错误:

Uncaught TypeError: Cannot read property 'top' of null ).

我应该更改什么才能使其正常工作?

o = document.createElement('img');
o.src = "img/birddead.png";
box.appendChild(o);
o.setAttribute("id", "devildead");
o.style.left = leftbird;
o.style.top = topbird;

// Function for moving the dead bird
var delay = 1;
var top = document.getElementById("devildead");

//Here I got the error
var currentTop = parseInt(getComputedStyle(devildead).top, 10);

// Start
setTimeout(move, delay);
function move(){
if (currentTop <= 480) {
currentTop += 2;
top.style.top = currentTop + "px";
setTimeout(move, delay);
}
}

最佳答案

我猜这是导致错误的行

var currentTop = parseInt(getComputedStyle(devildead).top, 10);   
// ^^ here

由于您没有 devildead 变量,出于某种原因,您将变量命名为 top

var currentTop = parseInt(getComputedStyle(top).top, 10);  

或者更好的是,不要将元素放在名为 top 的变量中,因为它会引起混淆

var devildead = document.getElementById("devildead");

var currentTop = parseInt(getComputedStyle(devildead).top, 10);

关于通过 Id 移动图像的 JavaScript 简单错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21067946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com