按下Shift键时JS限制鼠标通过轴移动(对于可拖动元素) [英] JS restrict mouse movement with axis when shift pressed (for draggable element)

查看:192
本文介绍了按下Shift键时JS限制鼠标通过轴移动(对于可拖动元素)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当按下Shift键时,我希望用户只能向上/向下或向左/向右移动鼠标. 我当前的粗略想法是在按下shift键时拦截所有运动,并使用事件模拟进一步传递所需的事件(该事件仅包含所需的轴运动). 我使用jQuery Draggable,所以另一个想法是确定何时按下shift并限制可拖动对象本身,但这可能需要研究可拖动代码,并且可能很耗时. 有任何想法如何以更优雅的方式做到这一点吗?

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?

推荐答案

通过应用可拖动的限制(仅在FF中测试)解决了该问题:

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

这篇关于按下Shift键时JS限制鼠标通过轴移动(对于可拖动元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆