1
我的目的是讓用戶點擊按鈕,當用戶點擊時,該字段顯示4,當用戶點擊並持有1秒以上時,字段顯示4.5。這裏是我的代碼:如何在jQuery中使用mousedown控制計時器?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").mousedown(function(e) {
clearTimeout(this.downTimer);
this.downTimer = setTimeout(function(){
$("#inp").val("4.5");
}, 1000);
}).mouseup(function(e) {
clearTimeout(this.downTimer);
// if no the holding is less than 1 sec,
// then nothing will be set, when mouseon, 4 is set to the field.
var el = document.getElementById('inp')
if(el.value == ""){
$("#inp").val("4");
}
});
});
</script>
</head>
<body>
<input type="text" id="inp">
<button id="btn">4</button>Good
</body>
</html>
然而,我的代碼有一定的侷限性,當4.5設置,它永遠不能被重新設置爲4。反正是有解決這個問題?我有一個想法,如果我可以控制一些代表計時器的變量,那麼我可以使用條件來完成這個任務。這可能在jQuery中嗎?
它的工作原理超時。完善! – TasteMyBiceps