一般我们的鼠标都是有左,中,右三个键。当我们按下鼠标时如何判断按下的是哪个键呢?
W3C DOM-Level-2 定义如下
W3C DOM 写道
During mouse events caused by the depression or release of a mouse button, button is used to indicate which mouse button changed state. The values for button range from zero to indicate the left button of the mouse, one to indicate the middle button if present, and two to indicate the right button. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.
其描述的很明确,0,1,2分别代表左,中,右三个键。以下分别在mousedown,mouseup,click,dbclick中测试。
01 <p id="p1">Test mousedown</p>
02 <p id="p2">Test mouseup</p>
03 <p id="p3">Test click</p>
04 <p id="p4">Test dbclick</p>
05
06 <script type="text/">
07 function $(id){return document.getElementById(id)}
08
09 var p1 = $('p1'), p2 = $('p2'), p3 = $('p3'), p4 = $('p4');
10 p1.onmousedown = function(e){
11 e = window.event || e;
12 alert(e.button);
13 }
14 p2.onmouseup = function(e){
15 e = window.event || e;
16 alert(e.button);
17 }
18 p3.onclick = function(e){
19 e = window.event || e;
20 alert(e.button);
21 }
22 p4.ondbclick = function(e){
23 e = window.event || e;
24 alert(e.button);
25 }
26 </script>
即:
所有浏览器,mousedown/mouseup事件中均能获取右键值,且都为2。
所有浏览器,click/dbclick事件中均不能获取到右键值。
以上可看到,判断鼠标按下了哪个键 ,应该选择合适的事件 。这里应选mousedown/mouseup。Opera10中仍然无法获取到中键的值,因为Opera压根不触发中键的事件(mousedown,mouseup,click,dbclick)。
以下代码将IE6/7/8的值转换成符合W3C标准的
01 var ie678 = !-[1,];
02 function getButton(e){
03 var code = e.button;
04 var ie678Map = {
05 1 : 0,
06 4 : 1,
07 2 : 2
08 }
09 if(ie678){
10 return ie678Map[code];
11 }
12 return code;
13 }