Check if mousedown with an if statement?

前端 未结 5 715
悲哀的现实
悲哀的现实 2021-02-02 17:16

Is it possible to do something like this:

if ($(this).mousedown() == true) {

I thought that would work but it doesn\'t.

Additio

5条回答
  •  没有蜡笔的小新
    2021-02-02 17:34

    The easiest way I can think of is to bind mousedown and mouseup event listeners to the document and update a global variable accordingly. In the mouseout event of your element you can check the state of that variable and act as appropriate. (Note: this assumes that you don't care whether or not the mouse was pressed down while over the div or not... you'll have to clarify your question around that).

    var down = false;
    $(document).mousedown(function() {
        down = true;
    }).mouseup(function() {
        down = false;  
    });
    $("#example").mouseout(function() {
        if(down) {
            console.log("down");  
        } 
        else {
            console.log("up");   
        }
    });
    

    Here's a working example of the above.

提交回复
热议问题