简体   繁体   中英

move image by pointing to the X, Y coordinates

I have the following code:

var currX = 0;
var currY = 0;
var player = $('#player');
//Checks to see which key is pressed down
        $(window).on('mousedown', function(e) { 
            currX = e.offsetX;
            currY = e.offsetY;
            console.log(e.offsetX + ', ' + e.offsetY);
        });


        player.css({
            left: function(index,value) { return (value + currX + 'px'); },
            top: function(index,value) { return  (value + currY + 'px'); }
        });

The image doesn't move at all. I console.log out both the offsets and they get printed out correctly.

Thanks!

You're setting the value of top and left to a function. That will be evaluated once, when that code is executed. You want to execute that code inside your mousedown listener if that's when you want the player to move.

you should apply this css in the mousedown event :

$(window).on('mousedown', function (e) {
    currX = e.offsetX;
    currY = e.offsetY;
    console.log(e.offsetX + ', ' + e.offsetY);
    player.css({
        left: currX + 'px',
        top: currY + 'px'
    });
});

FIDDLE

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