我尝试检测哪个鼠标按钮 - 如果用户在jQuery下的mousemove事件期间按下了,但是我得到了模棱两可的结果:
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
Run Code Online (Sandbox Code Playgroud)
码:
<!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>
Run Code Online (Sandbox Code Playgroud)
如何判断按下鼠标左键和没有按钮之间的区别?
Dar*_*JDG 60
您可以编写一些代码来跟踪鼠标左键的状态,使用一个小函数可以预先处理事件中的事件变量mousemove
.
要跟踪LMB的状态,请将事件绑定到文档级别mousedown
,mouseup
然后检查e.which
以设置或清除该标志.
预处理由tweakMouseMoveEvent()
我的代码中的函数完成.要支持IE版本<9,您必须检查窗口外是否释放鼠标按钮,如果是,则清除标记.然后,您可以更改传递的事件变量.如果e.which
原来是1(没有按钮或LMB)并且没有按下左按钮的当前状态,只需设置e.which
为0
,并在mousemove
事件的其余部分使用它来检查没有按下按钮.
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);
});
});
Run Code Online (Sandbox Code Playgroud)
在这里尝试现场演示:http://jsfiddle.net/G5Xr2/
Sph*_*xxx 19
大多数浏览器(Safari除外)*)现在支持MouseEvent.buttons
属性(注意:复数"按钮s "),按下鼠标左键时为1:
$('#whichkey').bind('mousemove', function(e) {
$('#log').html('Pressed: ' + e.buttons);
});
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/pdz2nzon/2
*)世界正在向前发展:
https://webkit.org/blog/8016/release-notes-for-safari-technology-preview-43/
https://trac.webkit.org/changeset/223264/webkit/
出于某种原因,当绑定到mousemove
event时,event.which
属性设置为1
if left button或none.
我改为mousedown
活动,它运作正常:
这是一个有效的例子:http://jsfiddle.net/marcosfromero/RrXbX/
jQuery代码是:
$('p').mousedown(function(event) {
console.log(event.which);
$('#button').text(event.which);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
62371 次 |
最近记录: |