博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
js中单击和双击事件的区分
阅读量:7024 次
发布时间:2019-06-28

本文共 2300 字,大约阅读时间需要 7 分钟。

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>
 
 
 
 
 
 

转载于:https://www.cnblogs.com/zhengao/p/7489648.html

你可能感兴趣的文章
python 如何在某.py文件中调用其他.py内的函数
查看>>
对症治疗过敏性鼻炎,依巴斯汀比氯雷他定更有效
查看>>
iOS 多线程 GCD part3:API
查看>>
UITableView UITableViewCell
查看>>
H5 Notes:Navigator Geolocation
查看>>
P2------总结
查看>>
A题笔记(3)
查看>>
Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy
查看>>
java 初始化字段(翻译自Java Tutorials)
查看>>
andorid 帧布局
查看>>
php 数组2
查看>>
c++和java字节高低位的转换
查看>>
XNA Game Studio4.0 Programming 随便读,随便记。
查看>>
用python实现字符串的替换
查看>>
统计vs机器学习,数据领域的“少林和武当”
查看>>
WCF概念
查看>>
用ChemDraw画3D图的方法
查看>>
上拉电阻大小对i2c总线的影响
查看>>
canvas绘图详解-04-矩形
查看>>
测试管理012:结对测试 - 不错的测试实践
查看>>