布尔函数来知道鼠标按钮的位置

boolean function to know position of mousebutton

本文关键字:按钮 位置 鼠标 函数 布尔      更新时间:2023-09-26

是否可以检查鼠标按钮的状态(按下或释放)。我知道这就是jquery中事件处理的目的,但我想知道,如果不需要更改按钮的位置(按下按钮即可释放,反之亦然)就不按下鼠标按钮,是否可以执行功能?

尝试以下代码,DEMO此处

$(document).mousedown (function () {
    $('#result').text('Pressed');
}).mouseup (function () {
    $('#result').text('Released');
});
$(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
});

您可以使用mousedownmouseup事件来检测更改的鼠标事件。此事件应绑定到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。当按下鼠标时,您可以读取按下的鼠标键(作为奖励)。