读jQuery之七(判断点击了鼠标哪个键)
http://www.cnblogs.com/snandy/archive/2011/06/15/2081265.html
jQuery丢弃了标准的 button 属性采用 which,这有点让人费解。
which 是Firefox引入的,IE不支持。which的本意是获取键盘的键值(keyCode)。
jQuery中的which即可以是键盘的键值,也可以是鼠标的键值。
即当判断用户按下键盘的哪个键时可以使用which,当判断用户按下鼠标的哪个键时也可以用which。它一举两用了。
源码
| 1 2 3 4 5 6 7 8 9 10 | // Add which for key eventsif( event.which == null&& (event.charCode != null|| event.keyCode != null) ) {    event.which = event.charCode != null? event.charCode : event.keyCode;}// Add which for click: 1 === left; 2 === middle; 3 === right// Note: button is not normalized, so don't use itif( !event.which && event.button !== undefined ) {    event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));} | 
标准的button采用0,1,2表示鼠标的左,中,右键。jQuery的which则使用用1,2,3。
还有一点让人不爽的是jQuery文档 event.which 中并没有提到which可以表示鼠标按键值,只提到了表示键盘按键值。
源码中的注释也让人误解。
| 1 | // Add which for click: 1 === left; 2 === middle; 3 === right | 
注意这里说的是click ,很容易让人使用click 事件,但实际上click事件中获取是错误的。
 下面就用 click 事件试试:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!DOCTYPE html><html><head><metacharset="utf-8"/><title></title><scripttype="text/javascript">    $(document).click(function(e){        alert(e.which);    })  </script></head><body></body></html> | 
| IE6/7/8 | IE9 | Firefox4 | Chrome12 | Safari | Opera | |
| 点击左键 | 0 | 1 | 1 | 1 | 1(不停弹出alert) | 1 | 
| 点击中键 | 不响应 | 2 | 2 | 2 | 2(不停弹出alert) | 不响应 | 
| 点击右键 | 仅弹出右键菜单 | 仅弹出右键菜单 | 3,弹出右键菜单 | 仅弹出右键菜单 | 仅弹出右键菜单 | 仅弹出右键菜单 | 
可以看到使用 click 事件并不能按照jQuery设想的那样左,中,右键对应的1,2,3值。各浏览器下均不一致,且右键根本获取不到,Safari中还不停的弹出alert。
因此,应该使用 mousedown / mouseup 事件则达到jQuery的设想。jQuery的注释误导了人。
此外即使使用 mousedown / mouseup 事件,Opera中也无法获取中键的值。Opera的恶心做法令jQuery也无能为力。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号