jQuery Draggable() and keyboard control

前端 未结 2 1893
故里飘歌
故里飘歌 2021-02-08 17:17

Hey there, I have a page with the jQuery Draggable() enabled on #person and that #person is constrained to #map.

(link to plugin:

相关标签:
2条回答
  • 2021-02-08 17:46

    Unfortunately, jQuery UI Draggable doesn't expose any methods to manually change the element's position. You will have to track the #person's position manually when moving it with the keyboard, and stop moving it when it is about to exceed the bounds of the #map.

    You can use jQuery methods such as .offset() and .position() methods to find reliable positions for elements.

    For instance:

    $(document).bind(
        'keydown',
        function(event) {
    
            switch(event.which) {
                case 37: {
    
                    var character = $(characterName);
                    var map = $('#map');
    
                    if((character.offset().left - 40) >  map.offset().left) {
                        character.animate(
                            {
                                left: '-=40'
                            },
                            250,
                            function(){}
                        );
                    }
    
                    break;
                }
            }
        }
    );
    
    0 讨论(0)
  • 2021-02-08 17:54

    If someone feels a bit lazy, this is what I just coded (simplified):

    $('body').on('keypress', handleKeys);
    
    function handleKeys(e) {
        var position, 
            draggable = $('#draggable'),
            container = $('#container'),
            distance = 1; // Distance in pixels the draggable should be moved
    
        position = draggable.position();
    
        // Reposition if one of the directional keys is pressed
        switch (e.keyCode) {
            case 37: position.left -= distance; break; // Left
            case 38: position.top  -= distance; break; // Up
            case 39: position.left += distance; break; // Right
            case 40: position.top  += distance; break; // Down
            default: return true; // Exit and bubble
        }
    
        // Keep draggable within container
        if (position.left >= 0 && position.top >= 0 &&
            position.left + draggable.width() <= container.width() &&
            position.top + draggable.height() <= container.height()) {
            draggable.css(position);
        }
    
        // Don't scroll page
        e.preventDefault();
    }
    
    0 讨论(0)
提交回复
热议问题