+ 3
How can i make this object move more than ones?
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <img src=" https://ichef.bbci.co.uk/images/ic/480x270/p05394v7.jpg " width="100" height="100" id="YourObject" style="position:relative;" > <br /> <button onclick="move();">Move</button> </body> </html> //js function move() { var obj = document.getElementById("YourObject"); obj.style.left = 50 + 'px'; }
6 Respostas
+ 2
Try change the code to
var left = Number(obj.style.left.replace('px',''));
obj.style.left = (left + 50) + 'px';
+ 2
Make THIS your js:
var left = 0;
setInterval(function(){
var obj = document.getElementById("yourObject");
obj.style.left = left + "%";
left = (left >= 100)? 0: left+=5;
}, 50);
+ 1
instead of using the number 50 you could use a variable that goes up everytime you press the button
+ 1
thanks a lot @Calvin but can you help explain more on this line of code?
Number(obj.style.left.replace('px',''));
+ 1
the solution of Calvin is perfect +1
0
you get the obj.style.left value in the var left without px and cast it in Number.
if obj.style.left = 100px then left = 100
so, after you can add 50 to left value to move your img