2017-08-09 78 views

回答

0

這裏,如果你按住按鈕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); 
}); 
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>

相關問題