在mousemove()事件处理程序中按下了哪个鼠标键?

时间:2012-04-12 08:09:37

标签: javascript jquery dom

我使用JQuery 1.7来处理事件。

function objToStr(obj) {
    return ...string representation of the object
}
$slider.mousedown(function(e) {
    console.log("$slider.mousedown:\n" + objToStr(e) );
});

$slider.mousemove( function(e) {
    console.log("$slider.mousemove:\n" + objToStr(e) );
});

以下是结果:

$slider.mousedown: 
altKey = false
 attrChange = undefined 
attrName = undefined 
bubbles = true 
button = 0 
buttons = undefined 
cancelable = true 
clientX = 319 
clientY = 13 
ctrlKey = false 
currentTarget = object 
data = null 
delegateTarget = object 
eventPhase = 3 
fromElement = undefined 
handleObj = object
isDefaultPrevented = (function) 
isImmediatePropagationStopped = (function) 
isPropagationStopped = (function) 
jQuery17209754494933906718 = true 
metaKey = false 
offsetX = undefined 
offsetY = undefined 
originalEvent = object 
pageX = 319 
pageY = 13 
preventDefault = (function) 
relatedNode = undefined 
relatedTarget = null 
screenX = 2876 
screenY = 223 
shiftKey = false 
srcElement = undefined 
stopImmediatePropagation = (function) 
stopPropagation = (function) 
target = object 
timeStamp = 869699957 
toElement = undefined 
type = "mousedown" 
view = object 
which = 1


$slider.mousemove: 
currentTarget = object
data = null 
delegateTarget = object 
exclusive = undefined 
handleObj = object 
isDefaultPrevented = (function) 
isImmediatePropagationStopped = (function) 
isPropagationStopped = (function) 
isTrigger = true 
jQuery17209754494933906718 = true 
namespace = "" 
namespace_re = null 
preventDefault = (function) 
result = undefined 
stopImmediatePropagation = (function) 
stopPropagation = (function) 
target = object 
timeStamp = 1334151903323 
type = "mousemove"

我需要e.which访问mousemove,但显然它没有传递给事件处理程序?

我不想使用jQuery: Detecting pressed mouse button during mousemove event中建议的标记算法。因为如果用户在浏览器窗口外拖动鼠标按钮并将其释放到那里,当鼠标返回浏览器窗口时,仍然认为它被按下了。然后我必须添加处理程序,当鼠标离开窗口时,它太多了。有没有更简单的方法来知道在mousemove()的事件处理程序中按下了哪个鼠标按钮?

2 个答案:

答案 0 :(得分:3)

我会想象,因为它是一个移动事件,当时发现什么键被按下并不被认为是最重要或最有效的,特别是因为事件频繁发生。因此,您需要为mouseupmousedown举办活动。

var leftMButtonDown = false;

$slider.mousedown(function(e) {
    if(e.which === 1) leftMButtonDown = true;
});

$(document).mouseup(function(e) {
    if(leftMButtonDown && e.which === 1) leftMButtonDown = false;
});

$slider.mousemove(function(e) {
    if(leftMButtonDown == true) {
        console.log('Left mouse button was down on mousemove event');
    }
});

你必须为鼠标右键等添加更多变量

答案 1 :(得分:1)

<body>
<div id="div" style=" height: 100px; border:1px solid red"></div>

<script>
  document.mouseState=-1; //global check mouse state

  document.onmousedown=function(e){
    document.mouseState=e.button;
  }
  document.onmouseup=function(e){
    document.mouseState=-1;
  }

  var d=document.getElementById('div');
  d.onmousemove= function(e){
    d.innerHTML+='; '+document.mouseState;

  }

</script>
</body>