按住按钮不会在单击时触发

Press and hold button does not fire onClick

本文关键字:单击 按钮      更新时间:2023-09-26

我的HTML5应用程序中的按钮有问题。

当我按下按钮时,视频播放器会运行并播放本地存储的视频。我现在的问题是,当我按住按钮并释放它时,它不会触发视频播放器。我在按钮上使用点击事件。

我想实现这一点,如果我按住按钮然后释放它,它会触发与我在 onclick 中使用的事件相同的事件。

使用onmouseup事件。

var button = //your button
button.onmouseup = function() {
//your logic
}

实际上,onmousedown 事件而不是 onClick 就可以了。

再次使用相同的语法:

爪哇语

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

jQuery

function clickFunction(){
   $(button).onmousedown(function(){
       //code goes here
   });
};

您应该使用布尔值来保存当前状态。

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
};

小提琴:链接