简单的onclick事件只工作一次

时间:2012-09-03 03:05:40

标签: javascript html css dom

请帮助)为什么这种结构不起作用?增量仅发生一次。

var player = document.getElementById("player");
var button = document.getElementById("button");

function moveDown(object) {
    object.style.top += 32;
}

button.onclick = function() {
    moveDown(player);
}

2 个答案:

答案 0 :(得分:0)

尝试使用:

object.style.top = parseInt(object.style.top, 10) + 32;

而不是

object.style.top+=32;

(并确保玩家的position设置为absoluterelative

答案 1 :(得分:0)

演示:http://jsfiddle.net/SrQUh/1/

var player = document.getElementById("player");
var button = document.getElementById("button");

function moveDown(object) {
  object.style.top = parseInt(object.style.top || 0) + 32 + 'px';
}

button.onclick = function() {
    moveDown(player);
}​