listen to mouse hold event on website?

前端 未结 4 860
無奈伤痛
無奈伤痛 2020-12-15 09:16

I know \'mousedown\' is when user press the mouse, \'mouseup\' is when user release the mouse. But I want to listen the event after user press the mouse and hold it until it

相关标签:
4条回答
  • 2020-12-15 09:22

    var setint  = '';
    $(document).ready(function() {
    var val = 0;
    $('#hold').on('mousedown',function (e) {
       clearInterval(setint);
       val = 0;
       setint = setInterval(function () {
           $("#putdata").val(++val);
            console.log("mousehold");
       },50);
    });
    $('#hold').on("mouseleave mouseup", function () {
       val = 0;
       $("#putdata").val(val);
       clearInterval(setint);
    });
    });
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    </head>
    <body>
    <input type="text" id="putdata" />
    <input type="button" value="mouse-hold" id="hold" />
    </body>
    <html>

    0 讨论(0)
  • 2020-12-15 09:24

    If you want the hold state then it will be the state when you are in mousedown event state for a while. This state exists when you press mousedown but not mouseup. Hence you need to take a variable which records the current state of the event.

    JS

    $('div').on('mousedown mouseup', function mouseState(e) {
        if (e.type == "mousedown") {
            //code triggers on hold
            console.log("hold");
        }
    });
    

    Working Fiddle

    0 讨论(0)
  • 2020-12-15 09:33

    From jquery.com :

    HTML :

    <p>Press mouse and release here.</p>
    

    Script:

    $("p").mouseup(function(){
        $(this).append('<span style="color:#F00;">Mouse up.</span>');
    }).mousedown(function(){
        $(this).append('<span style="color:#00F;">Mouse down.</span>');
    });
    

    Full url : http://api.jquery.com/mousedown/

    0 讨论(0)
  • 2020-12-15 09:37

    Try this

    Add respective mouse events to folowing functions

    mouse = false;
    function mousedown()
    {
      mouse = true;
      callEvent();
    }
    function mouseup()
    {
      mouse =false;
    }
    function callEvent()
    {
     if(mouse)
     {
       // do whatever you want
       // it will continue executing until mouse is not released
    
    
       setTimeout("callEvent()",1);
     }
     else
     return;
    }
    
    0 讨论(0)
提交回复
热议问题