булева функция для определения положения кнопки мыши - PullRequest
2 голосов
/ 12 января 2012

можно проверить состояние кнопки мыши (нажата или отпущена). Я знаю, что это и есть цель обработки событий в jquery, но мне интересно, можно ли было бы сделать функцию, если кнопка мыши не нажата без необходимости изменения ее положения (нажатие для отпускания или наоборот)?

Ответы [ 3 ]

3 голосов
/ 12 января 2012

Попробуйте код ниже, ДЕМО здесь

$(document).mousedown (function () {
    $('#result').text('Pressed');
}).mouseup (function () {
    $('#result').text('Released');
});
1 голос
/ 12 января 2012
$(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
});
1 голос
/ 12 января 2012

Вы можете использовать события 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

В логическом контексте возвращаемое значение функции оценивается как ложное, если мышьвниз.Когда мышь нажата, вы можете прочитать, какая клавиша мыши нажата (в качестве бонуса).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...