简体   繁体   中英

Adding a limit to moving a div with arrow keys

Hi I have added in functionality (found on stackoverflow) to make my div move left or right once the user holds down one of the arrow keys. All works as it should.

I want to know is there a way to stop the div from moving once it has reached the "end" or once it has moved a certain amount of pixels.

Code I have is below

$(document).keydown(function(e) {
switch (e.which) {
case 37:
    $('#block').stop().animate({
        left: '-=50'
    }); //left arrow key
    break;

case 39:
    $('#block').stop().animate({
        left: '+=50'
    }); //right arrow key
    break;

}
})

Sure, take a look at this fiddle: http://jsfiddle.net/ArtBIT/V7qcK/

var KEY = {
    LEFT: 37,
    RIGHT: 39
}
var boundaries = {
    left: 0,
    right: 200
}
$(document).keydown(function(e) {
    var position = $('#block').position();

    switch (e.which) {
    case KEY.LEFT:

        $('#block').stop().animate({
            left: Math.max(boundaries.left, position.left - 50)
        }); 
        break;

    case KEY.RIGHT:
        $('#block').stop().animate({
            left: Math.min(boundaries.right, position.left + 50)
        });
        break;
    }
});​

Or this one http://jsfiddle.net/ArtBIT/8PWCR/1/ for 2D movement

Get the current offset and then handle it:

var max = 1000;

$(document).keydown(function(e) {
    switch (e.which) {

        case 37:
            if($('#block').offset().left > 50)
            {
                $('#block').stop().animate({ left: '-=50' });
            }
            break;

        case 39:
            if($('#block').offset().left < (max - 50)
            {
                $('#block').stop().animate({ left: '+=50' });
            }
            break;

    }
});

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