开发者

JS restrict mouse movement with axis when shift pressed (for draggable element)

开发者 https://www.devze.com 2023-01-09 08:28 出处:网络
When shift button pressed I want user to be able to only move mouse strictly up/down or left/right. My current rough idea is to intercept all movements when shift is pressed and use events simulation

When shift button pressed I want user to be able to only move mouse strictly up/down or left/right. My current rough idea is to intercept all movements when shift is pressed and use events simulation to pass needed event (which will contain only needed axis movement) further. I use jQuery Draggable so other idea is to determine when shift is pressed and restrict draggable itself but this might require investigating draggable code and might be time consumi开发者_如何转开发ng. Any ideas how to do this in more elegant way?


Solved by applying draggable restrictions (tested only in FF):

     function applyDragRestriction(event, prevPosition) {
            if ($( ".componentPlaced" ).draggable( "option", "axis" )) return;
            if (Math.abs(event.clientX - prevPosition.x) < Math.abs(event.clientY - prevPosition.y)) {
                $('.componentPlaced').draggable({ axis: 'y' });
            } else {
                $('.componentPlaced').draggable({ axis: 'x' });
            }
        }

    function applyShiftHandler(event) {
        if (isShiftDown) applyDragRestriction(event, oldMousePositions);
        oldMousePositions = {x: event.clientX, y: event.clientY};
    }

    function checkShiftDown(event) {
        if (event.keyCode == KeyEvent.DOM_VK_SHIFT) {
           isShiftDown = true;
        }
    }

    function checkShiftUp(event) {
        if (event.keyCode == KeyEvent.DOM_VK_SHIFT) {
            cancelDragRestriction();
            isShiftDown = false;
        }
    }

function cancelDragRestriction() {
    $('.componentPlaced').draggable({ axis: null });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消