简体   繁体   中英

Moving image left and right with jQuery

OK, here is the updated, and working code. Making the image relative did the trick. Now the only thing left is as soon as I remove my finger from the key, I want the image to stop moving. How would I properly use the keyup?

<html>
<head></head>
<body>
        <img id="pic" src="run0.png" alt="image" height="100" width="100" style="position: relative;"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script> 

$(document).keydown(function(event){
     var keycode = (event.keyCode ? event.keyCode : event.which);                
                if(keycode == '39'){
                    $("#pic").animate({
                         left: '+=10px',
                    });
                }
     });

</script>
    </body>
</html>

I would also prefer no to have to put an image on the document first with HTML, but to just append it to the document from Javascript/jQuery. And if anyone can help me do it with pure Javascript that would be appreciated.

Arrow keys can't be detected with keypress. Read : Detecting arrow key presses in JavaScript

Also for the left property to affect the image.. it should be absolutely placed in page. Here is a sample demo : https://jsfiddle.net/6haxsbz9/

HTML:

<img id="pic" src="https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="image" width="100" />

CSS:

img {
    position:absolute;
    left:10px;
    top:10px;
}

JS:

$(function () {

    $(document).keydown(function (event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '39') {
            $("#pic").animate({
                left: '+=5px',
            });
        }
    });

});

First, as said in the comments, fix syntax errors!

Then you want to animate your pic with the CSS property left which is part of CSS position . If you add that to your image it should work (I just took keycode 97 for a because I don't know what 39 is):

HTML:

<img id="pic" src="run0.png" alt="image" height="100" width="100" />

CSS:

#pic {
    position: absolute;
    left: 20px;
}

jQuery:

$(document).keypress(function (event) {
    // var keycode = (event.keyCode ? event.keyCode : event.which);

    console.log(event.keyCode);
    if (event.keyCode == '97') {
        $("#pic").animate({
            left: '+=5px',
        });
    }
});

See jsfiddle: https://jsfiddle.net/914m6ut3/

尝试为图像添加相对位置:

<img id="pic" src="run0.png" alt="image" height="100" width="100" style="position: relative;"  />

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