press and hold button javascript

前端 未结 3 912
余生分开走
余生分开走 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: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

提交回复
热议问题