I tried to detect which mouse button -if any- is the user pressing during a mousemove event under jQuery, but I'm getting ambiguous results:

no button pressed:      e.which = 1   e.button = 0
left button pressed:    e.which = 1   e.button = 0
middle button pressed:  e.which = 2   e.button = 1
right button pressed:   e.which = 3   e.button = 2

代码:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>

<input id="whichkey" value="type something">
<div id="log"></div>
<script>$('#whichkey').bind('mousemove',function(e){ 
  $('#log').html(e.which + ' : ' +  e.button );
});  </script>

</body>
</html>

How can I tell the difference between left mouse button pressed and no button at all?

推荐答案

您可以编写一些代码来跟踪鼠标左键的状态,并且使用一些函数可以预处理mousemove事件中的事件变量.

要跟踪LMB的状态,请将事件绑定到mousedownmouseup的文档级,并判断e.which以设置或清除标志.

The pre-processing is done by the tweakMouseMoveEvent() function in my code. To support IE versions < 9, you have to check if mouse buttons were released outside the window and clear the flag if so. Then you can change the passed event variable. If e.which was originally 1 (no button or LMB) and the current state of the left button is not pressed, just set e.which to 0, and use that in the rest of your mousemove event to check for no buttons pressed.

在我的示例中,mousemove处理程序只需调用传递当前事件变量的tweak函数,然后输出e.which的值.

$(function() {
    var leftButtonDown = false;
    $(document).mousedown(function(e){
        // Left mouse button was pressed, set flag
        if(e.which === 1) leftButtonDown = true;
    });
    $(document).mouseup(function(e){
        // Left mouse button was released, clear flag
        if(e.which === 1) leftButtonDown = false;
    });

    function tweakMouseMoveEvent(e){
        // Check from jQuery UI for IE versions < 9
        if ($.browser.msie && !e.button && !(document.documentMode >= 9)) {
            leftButtonDown = false;
        }

        // If left button is not set, set which to 0
        // This indicates no buttons pressed
        if(e.which === 1 && !leftButtonDown) e.which = 0;
    }

    $(document).mousemove(function(e) {
        // Call the tweak function to check for LMB and set correct e.which
        tweakMouseMoveEvent(e);

        $('body').text('which: ' + e.which);
    });
});

Try a live demo here: http://jsfiddle.net/G5Xr2/

Jquery相关问答推荐

JQuery日期 Select 器未设置从jQuery中 Select 的月份起90天或3个月

使用动态类名的gm_addStyle?

使用 howler.js 中的变量播放多种声音

Bootstrap 3模态框和video.js视频未正确调整大小

退出 jquery.each 循环后

修改对象数组中的对象属性

使用 jQuery 为 box-shadow 设置动画的正确方法

jquery如何捕获输入键并将事件更改为选项卡

jQuery/JavaScript 碰撞检测

window.onbeforeunload 和 window.onunload 在 Firefox、Safari、Opera 中不起作用?

jQuery绑定到粘贴事件,如何获取粘贴的内容

如何使用给定的 url 判断图像是否存在?

Jquery查找所有以字符串开头的ID?

在 jQuery 中处理多个 ID

如何在实际图像下载时显示加载图像

Rails 无法正确解码来自 jQuery 的 JSON(数组变成带有整数键的散列)

如何使用 javascript (jquery) 将整数值添加到返回字符串的值中?

jQuery attr 与props ?

javascript,是否有像 isArray 这样的 isObject 函数?

.success() 和 .complete() 之间的区别?