JavaScript 鼠标事件有以下8种
mousedown
鼠标的键钮被按下。
mouseup
鼠标的键钮释放弹起。
click
鼠标左键(或中键)被单击。
事件触发顺序是:mousedown -> mouseup -> click
dblclick
鼠标左键(或中键)被双击。
事件触发顺序是:mousedown -> mouseup -> click -> mousedown -> mouseup -> click -> dblclick。
contextmenu
弹出右键菜单,它可能是鼠标右键触发的,也可能是键盘的菜单键触发的。
mouseover
鼠标移动到目标上方。
mouseout
鼠标从目标上方移出。
mousemove
鼠标在目标上方移动
注意:事件名称大小写敏感。若需要监听以上事件,则在事件名的前面加个on即可。
事件区别
onmouseover、nmouseout:鼠标移动到自身时候会触发事件,同时移动到其子元素身上也会触发事件
onmouseenter、onmouseleave:鼠标移动到自身是会触发事件,但是移动到其子元素身上不会触发事件
全局事件对象event
event.x
事件发生时鼠标的位置
event.y
事件发生时鼠标的位置
button
鼠标的哪一个键触发的事件
0
鼠标左键
1
鼠标中键
2
鼠标右键
代码范例
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<html> <body> <script type="text/javascript"> function appendText(str) { document.body.innerHTML += str + "<br/>"; } document.onmousedown = function() { appendText("onmousedown"); appendText("button = " + event.button); appendText("(x,y) = " + event.x + "," + event.y); } document.onmouseup = function() { appendText("onmouseup"); } document.onclick = function() { appendText("onclick"); } document.ondblclick = function() { appendText("ondblclick"); } document.oncontextmenu = function() { appendText("oncontextmenu"); } document.onmouseover = function() { appendText("onmouseover"); } document.onmouseout = function() { appendText("onmouseout"); } document.onmousemove = function() { appendText("mousemove"); } </script> </body></html> |
这里使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,得到如下运行结果:

原文:https://www.cnblogs.com/raineliflor/p/10397036.html