Home  >  Article  >  Web Front-end  >  Read jQuery Part 7. Code to determine which mouse button is clicked_jquery

Read jQuery Part 7. Code to determine which mouse button is clicked_jquery

WBOY
WBOYOriginal
2016-05-16 18:05:391244browse

jQuery dropped the standard button attribute in favor of which, which is a bit puzzling.

which is introduced by Firefox and is not supported by IE. The original intention of which is to obtain the key value (keyCode) of the keyboard.

Which in jQuery can be the key value of the keyboard or the key value of the mouse.
That is, which can be used when determining which key of the keyboard the user pressed, and which can also be used when determining which key of the mouse the user pressed. It serves two purposes.
Source code

Copy code The code is as follows:

// Add which for key events
if ( 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 it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event. button & 4 ? 2 : 0 ) ));
}

The standard button uses 0,1,2 to represent the left, middle, and right mouse buttons. jQuery's which uses 1,2,3.

Another unpleasant thing is that the jQuery document event.which does not mention which can represent the mouse button value, but only mentions the keyboard button value.

The comments in the source code are also misleading.
Copy code The code is as follows:

// Add which for click: 1 === left ; 2 === middle; 3 === right

Note that this is click. It is easy for people to use the click event, but in fact, the acquisition of the click event is wrong.
Try using the click event below:
Copy the code The code is as follows:

< ;!DOCTYPE html>











测试结果
IE6/7/8 IE9 Firefox4 Chrome12 Safari Opera
点击左键 0 1 1 1 1(不停弹出alert) 1
点击中键 不响应 2 2 2 2(不停弹出alert) 不响应
点击右键 仅弹出右键菜单 仅弹出右键菜单 3,弹出右键菜单 仅弹出右键菜单 仅弹出右键菜单 仅弹出右键菜单

You can see that using the click event does not correspond to the 1, 2, and 3 values ​​​​for the left, middle, and right keys as jQuery imagined. It is inconsistent in each browser, and the right-click cannot be obtained at all, and alerts keep popping up in Safari.

Therefore, mousedown / mouseup events should be used to achieve jQuery's vision. jQuery's comments are misleading.

In addition, even if the mousedown / mouseup events are used, the value of the middle button cannot be obtained in Opera. Opera's disgusting practices make jQuery powerless.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn