简体   繁体   English

按住按钮 javascript

[英]press and hold button javascript

I'm having a problem with my button in my HTML5 application.我的 HTML5 应用程序中的按钮有问题。 When I press the button a Video player runs and plays the video that is stored locally.当我按下按钮时,视频播放器会运行并播放本地存储的视频。 My issue now is that when I hold the button and release it, it doesn't fire the video player.我现在的问题是,当我按住按钮并释放它时,它不会触发视频播放器。 I'm using an Onclick event on my button.我在按钮上使用了 Onclick 事件。

The thing that I want to achieve is that if I press and hold the button and then release it, it fires the same event as the one I use with the onclick.我想要实现的是,如果我按住按钮然后释放它,它会触发与我在 onclick 中使用的事件相同的事件。 I'm planning to do this by using JavaScript but I have no idea how to fix this problem.我打算通过使用 JavaScript 来做到这一点,但我不知道如何解决这个问题。 Any suggestions would be very appreciated.任何建议将不胜感激。

Thanks in advance.提前致谢。

Use onmouseup event.使用onmouseup事件。

var button = //your button

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

}

Actually onmousedown event instead of onClick will do the trick.实际上,onmousedown 事件而不是onClick 可以解决问题。

Again the same syntax:同样的语法:

Javascript Javascript

<button onmousedown ="clickFunction()">Click me!</button>

function clickFunction(){
//code goes here
}

jQuery jQuery

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

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小提琴:链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM