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


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不起作用。是要做的事情吗与联想性?

问题是当你调用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) + "%";
}
function moveRight(obj){
    obj.style.left = parseInt(obj.style.left) + 0.5 + "%";
}

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

最新更新