Domanda

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

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

The code here is supposed to move my image object to the left and to the right by updating percentages instead of pixels. moveLeft works but moveRight doesn't. Is it something to do with associativity?

È stato utile?

Soluzione

The problem is that when you call parseInt() it returns the value rounded down. So you're actually not moving by half percent, but one percent. This way, the best solution is to increment in 1 on every step:

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

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

Altri suggerimenti

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

You use style.left instead of style.right

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top