我需要实现一个按钮,当我单击并按住它5秒钟时,它会调用一个JavaScript函数,当我释放按钮时它会取消该调用。我怎么能这样做?
这样的事情:
答案 0 :(得分:2)
这是一个jsfiddle,如果您按住按钮5秒钟将触发警报但如果在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);
});
答案 1 :(得分:1)
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>