简体   繁体   中英

Move an element with arrow keys

function docReady()
{
    image = document.getElementById("someImage");
    window.addEventListener("keydown", moveImage);
}

function moveImage(e)
{
    if (e.keyCode == 37)
        image.style.left = parseInt(image.style.left) - 5 + 'px';

    if (e.keyCode == 38)
        image.style.top = parseInt(image.style.top) - 5 + 'px';

    if (e.keyCode == 39)
        image.style.left = parseInt(image.style.left) + 5 + 'px';

    if (e.keyCode == 40)
        image.style.top = parseInt(image.style.top) + 5 + 'px';

    console.log(image.style.left + ', ' + image.style.top);
}

So the code above is supposed to move an image around. However, it doesn't. The console returns blanks for image.style.left and image.style.top . Could you help me with fixing it?

PS If you would be so kind, can you also make it so that if the image is on the screen borders it will stop moving? Thank you so much!

You are missing some steps indeed.

To be precise, you should:

  • create the variable image outside the function (ie, declare it global)
  • set the initial values of top , left
  • set the position of your element to absolute . Default is static and it doesn't support moving/styling with top/left/right/bottom.
  • call the whole thing on page load

And here's what you get once you follow the above steps:

 window.onload = docReady; var image; function docReady() { image = document.getElementById("someImage"); window.addEventListener("keydown", moveImage); image.style.left = 0; image.style.top = 0; } function moveImage(e) { if (e.keyCode == 37) image.style.left = parseInt(image.style.left) - 5 + 'px'; if (e.keyCode == 38) image.style.top = parseInt(image.style.top) - 5 + 'px'; if (e.keyCode == 39) image.style.left = parseInt(image.style.left) + 5 + 'px'; if (e.keyCode == 40) image.style.top = parseInt(image.style.top) + 5 + 'px'; console.log(image.style.left + ', ' + image.style.top); } 
 #someImage{ position:absolute; } 
 <div id = "someImage"> not an image but a test </div> 

(For the simplicity I'm using a plain text element instead of image, but that doesn't matter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM