Javascript - style.left将更新为减法但不添加

时间:2013-07-30 22:19:59

标签: javascript styles associativity

function moveLeft(obj){ 
    obj.style.left = parseInt(obj.style.left) - 0.5 + "%";
}

function moveRight(obj){
    obj.style.left = parseInt(obj.style.left) + 0.5 + "%";
}

这里的代码应该通过更新百分比而不是像素来将我的图像对象向左和向右移动。 moveLeft有效但moveRight没有。这是可以做的事情 与结合?

2 个答案:

答案 0 :(得分:0)

function moveRight(obj){
    obj.style.left = parseInt(obj.style.left) + 0.5 + "%";
}

您使用style.left而不是style.right

答案 1 :(得分:0)

问题是当你调用parseInt()时它会返回向下舍入的值。所以你实际上没有移动百分之一,而是百分之一。这样,最好的解决方案是每步增加1:

function moveLeft(obj){ 
    obj.style.left = (parseInt(obj.style.left, 10) - 1) + "%";
}

function moveRight(obj){
    obj.style.left = (parseInt(obj.style.left, 10) + 1) + "%";
}