我需要實現一個按鈕,當我點擊並按住它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