JS restrict mouse movement with axis when shift pr

2019-07-30 01:34发布

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 consuming. Any ideas how to do this in more elegant way?

1条回答
2楼-- · 2019-07-30 02:37

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 });
}
查看更多
登录 后发表回答