是否可以检查鼠标按钮的状态(按下或释放)。我知道这是jquery中事件处理的目的,但是我想知道如果没有按下鼠标按钮而不需要改变按钮的位置(按下释放),是否可以执行一个功能反之亦然)?
答案 0 :(得分:3)
尝试以下代码,DEMO此处
$(document).mousedown (function () {
$('#result').text('Pressed');
}).mouseup (function () {
$('#result').text('Released');
});
答案 1 :(得分:1)
您可以使用mousedown
和mouseup
事件来检测已更改的鼠标事件。此事件应绑定到window
。 演示:http://jsfiddle.net/uwzbn/
var mouseState = (function(){
var mousestatus = 0;
$(window).mousedown(function(e) {
mousestatus = e.which;
}).mouseup(function(e){
mousestatus = 0;
});
return function() {
return mousestatus;
}
})();
此函数返回四个可能的值:
0 Mouse released false
1 Left click true
2 Middle click true
3 Right click true
在布尔上下文中,当鼠标未关闭时,函数返回值的计算结果为false。按下鼠标时,您可以读取按下的鼠标键(作为奖励)。
答案 2 :(得分:1)
$(function () {
//setup flag for the state of the mouse button and create an object that converts an event type into a boolean for the flag
var mousePressed = false,
mouseConvert = {
mousedown : true,
mouseup : false
};
//bind to the document's mousedown and mouseup events to change the flag when necessary
$(document).on('mousedown mouseup', function (event) {
//set the flag to the new state of the mouse button
mousePressed = mouseConvert[event.type];
//if you only want to watch one mouse button and not all of them then
//you can create an if/then statement here that checks event.which
//and only updates the flag if it is the button you want, check-out Rob W.'s
//answer to see the different values for event.which with respect to the mouse
});
//now you can check the value of the `mousePressed` variable, if it is equal to `true` then the mouse is currently pressed
});