天天看点

js中单击和双击事件的区分

1.首先了解鼠标单击事件是所包含的事件。

mousedown 事件:

当鼠标指针移动到元素上方,并按下鼠标按键时,会发生 mousedown 事件。与 click 事件不同,mousedown 事件仅需要按键被按下,而不需要松开即可发生。

mouseup 事件:

  当在元素上放松鼠标按钮时,会发生 mouseup 事件。与 click 事件不同,mouseup 事件仅需要放松按钮。当鼠标指针位于元素上方时,放松鼠标按钮就会触发该事件。

click(单击)事件:

  当鼠标指针停留在元素上方,然后按下并松开鼠标左键时,就会发生一次 click。

dblclick(双击)事件:

  当鼠标指针停留在元素上方,然后按下并松开鼠标左键时,就会发生一次 click。在很短的时间内发生两次 click,即是一次 double click 事件。

2. 其次要了解鼠标点击事件中各个事件的执行顺序。

<!DOCTYPE html> <html >

<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 >

<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

继续阅读