1.首先了解鼠標單擊事件是所包含的事件。
mousedown 事件:
當鼠標指針移動到元素上方,並按下鼠標按鍵時,會發生 mousedown 事件。與 click 事件不同,mousedown 事件僅需要按鍵被按下,而不需要松開即可發生。
mouseup 事件:
當在元素上放松鼠標按鈕時,會發生 mouseup 事件。與 click 事件不同,mouseup 事件僅需要放松按鈕。當鼠標指針位於元素上方時,放松鼠標按鈕就會觸發該事件。
click(單擊)事件:
當鼠標指針停留在元素上方,然后按下並松開鼠標左鍵時,就會發生一次 click。
dblclick(雙擊)事件:
當鼠標指針停留在元素上方,然后按下並松開鼠標左鍵時,就會發生一次 click。在很短的時間內發生兩次 click,即是一次 double click 事件。
2. 其次要了解鼠標點擊事件中各個事件的執行順序。
<!DOCTYPE html>
<html lang="en">
<head>
<title>鼠標點擊事件</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery.js"></script>
</head>
<body>
<input type="button" id="testBtn" value="單擊我或者雙擊我">
<script language="javascript">
var a = 0;
$("#testBtn").on("mousedown", function() {
console.log("this is mousedown event");
console.log("a=" + a++);
});
$("#testBtn").on("mouseup", function() {
console.log("this is mouseup event");
console.log("a=" + a++);
});
$("#testBtn").on("click", function() {
console.log("this is click event");
if (a == 2) {
$("#testBtn").css("background-color", "red");
}
if (a == 5) {
$("#testBtn").css("background-color", "green");
}
console.log("a=" + a++);
});
$("#testBtn").on("dblclick", function() {
console.log("this is dblclick event");
console.log("a=" + a++);
});
</script>
</body>
</html>
4.在雙擊的同時也發生了單擊事件,那么利用setTimeout和clearTimeout來實現對事件的清除。
<!DOCTYPE html>
<html lang="en">
<head>
<title>去掉鼠標點擊事件</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery.js"></script>
</head>
<body>
<input type="button" id="testBtn" value="單擊我或者雙擊我">
<script language="javascript">
var a = 0;
var timeoutID = null;
$("#testBtn").on("click", function() {
// clearTimeout() 方法可取消由 setTimeout() 方法設置的 timeout。
clearTimeout(timeoutID);
// setTimeout() 方法用於在指定的毫秒數后調用函數或計算表達式
// 利用時間的延遲來解決雙擊事件對單擊事件的影響
timeoutID = window.setTimeout(function() {
console.log("this is click event");
if (a == 2) {
$("#testBtn").css("background-color", "red");
}
if (a == 5) {
$("#testBtn").css("background-color", "green");
}
console.log("a=" + a++);
}, 200);
});
$("#testBtn").on("dblclick", function() {
clearTimeout(timeoutID);
console.log("this is dblclick event");
console.log("a=" + a++);
});
</script>
</body>
</html>