press and hold button javascript

前端 未结 3 911
余生分开走
余生分开走 2021-01-25 19:31

I\'m having a problem with my button in my HTML5 application. When I press the button a Video player runs and plays the video that is stored locally. My issue now is that when I

相关标签:
3条回答
  • 2021-01-25 20:13

    Use onmouseup event.

    var button = //your button
    
    button.onmouseup = function() {
    //your logic
    
    }
    
    0 讨论(0)
  • 2021-01-25 20:23

    Actually onmousedown event instead of onClick will do the trick.

    Again the same syntax:

    Javascript

    <button onmousedown ="clickFunction()">Click me!</button>
    
    function clickFunction(){
    //code goes here
    }
    

    jQuery

    function clickFunction(){
       $(button).onmousedown(function(){
           //code goes here
       });
    };
    
    0 讨论(0)
  • 2021-01-25 20:27

    you should use a boolean to save the current state.

    var mouse_is_down = false;
    var current_i = 0;              // current_i is used to handle double click (to not act like a hold)
    
    var button = document.querySelector("#myButton");
    
    button.onmousedown = function(){
        mouse_is_down = true;
    
        // Do thing here for a mousedown event
    
        setTimeout(
            (function(index){
                return function(){
                    if(mouse_is_down && current_i === index){
                        //do thing when hold                        
                    }
                };
            })(++current_i), 500); // time you want to hold before fire action in milliseconds
    };
    
    button.onmouseup = function(){
        mouse_is_down = false;
        current_i++;
    
        // Do thing here for a mouseup event
    };
    

    Fiddle : link

    0 讨论(0)
提交回复
热议问题