我在我的横幅 div 中创建了一个僵尸 img,但在创建后我无法让 img 移动到左侧。
createZombie 函数在定时器上:
createZombieTimer = window.setInterval(createZombie, 1000);
这是在随主体加载的 init() 中。
function createZombie(){
var imgElem = document.createElement("img");
imgElem.src = "img/zombie_walk_right.gif";
var newZom = document.getElementById('banner').appendChild(imgElem);
newZom.style.height = "40px";
newZom.style.width = "auto";
newZom.style.display = "block";
newZom.style.marginLeft = "50px";
var zomPos = parseInt(newZom.style.marginLeft);
if (zomPos > 0) {
newZom.style.marginLeft = (zomPos + 50) + "px";
}
}
最佳答案
既然从评论中已经很清楚你想做什么,我就把它贴在这里作为答案。
您也可以使用纯 JavaScript 来完成此操作。您需要做的是使用 setInterval()
。这将每秒执行一个函数,您可以在其中更新元素的位置。
例子:
// Function to move the zombie by 50 pixels
function moveZombie()
{
// Select the zombie element (will need additional logic to select all of them, just an example)
zomElement = document.getElementById('zombie1');
zomPos = parseInt(zomElement.style.marginLeft);
zomElement.style.marginLeft = (zomPos + 50) + 'px';
}
// Call this function every second
setInterval(moveZombie(), 1000);
关于Javascript:在createElement之后移动新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22767518/