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

匆匆过客 提交于 2020-01-15 12:45:29

问题


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:


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 });
}


来源:https://stackoverflow.com/questions/3350227/js-restrict-mouse-movement-with-axis-when-shift-pressed-for-draggable-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!