我需要实现一个按钮,当我点击并按住它5秒钟时,它会调用一个JavaScript函数,当我释放按钮时,它将取消该调用。我怎样才能做到这一点?如何实现一个调用JavaScript函数的保持按钮?
事情是这样的:
我需要实现一个按钮,当我点击并按住它5秒钟时,它会调用一个JavaScript函数,当我释放按钮时,它将取消该调用。我怎样才能做到这一点?如何实现一个调用JavaScript函数的保持按钮?
事情是这样的:
这里,如果你按住按钮5秒钟,这将触发警报,但不会打电话报警,如果的jsfiddle您在5秒钟之前释放按钮。 这是通过设置一个超时,当你点击按钮,但释放按钮时清除超时。 (用了jQuery)
https://jsfiddle.net/ehozjeLn/1/
<div>
<input id="btnTesting" type="button" value="test" />
</div>
$('#btnTesting').mousedown(function(){
myTimeout = setTimeout(function(){ alert("Hello"); }, 5000);
});
$('#btnTesting').mouseup(function(){
clearTimeout(myTimeout);
});
var Handler = function() {
// create a function which sets an action to handle in 5 seconds.
this.clickHandler = function() {
var self = this;
this.timerId = setTimeout(function() {
console.log('fired!!!!');
self.timerId = null;
// do whatever here.
},5000)
};
//creat a function which will cancel the previously scheduled task.
this.cancelHandler = function() {
// fire cancel logic if needed
if (this.timerId) {
console.log('cancelling');
clearTimeout(this.timerId);
}
}
}
var h = new Handler();
//find an element to attach the event to.
var button = document.querySelector('button');
//wire up your event handlers to your element
button.addEventListener('mousedown', h.clickHandler.bind(h));
button.addEventListener('mouseup', h.cancelHandler.bind(h));
<button>Click Me</button>
你尝试过这么远吗? – freginold