Javascript-style.left将更新减法而不是加法

Javascript-style.left将更新减法而不是加法,javascript,styles,associativity,Javascript,Styles,Associativity,这里的代码应该通过更新百分比而不是像素来向左和向右移动图像对象。moveLeft有效,但moveRight无效。有什么事要做吗 有联想性吗 function moveLeft(obj){ obj.style.left = parseInt(obj.style.left) - 0.5 + "%"; } function moveRight(obj){ obj.style.left = parseInt(obj.style.left) + 0.5 + "%"; } 您使用sty

这里的代码应该通过更新百分比而不是像素来向左和向右移动图像对象。moveLeft有效,但moveRight无效。有什么事要做吗 有联想性吗

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

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

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

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

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

试过了,输出没有差别:(
function moveLeft(obj){ 
    obj.style.left = (parseInt(obj.style.left, 10) - 1) + "%";
}

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