Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the left and right mouse button and middle button events in JS

Shulou Source: shulou.com Published: 2022-06-02 18:35:17 09月30日 Update

This article mainly explains "how to achieve the left and right mouse button and middle button event in JS". The explanation in the article is simple and clear and easy to learn and understand. please follow the editor's train of thought to study and learn "how to achieve the left and middle mouse button event in JS".

In 3D scenes, it is sometimes necessary to judge the events of the mouse, except for the click events used, only the left mouse button is valid, while the right button is invalid. The left / right button of the mouse event is valid for onmousedown and onmouseup. Please see the information on W3C for details.

How to operate the middle mouse button

First, you need to bind the mousedown and mouseup events for window

Element object .addEventListener ('mousedown', handler fun)

one

Then, judging the value of button, the button event property returns an integer indicating which mouse button was clicked when the event was triggered.

Button: returns which mouse button is clicked when the event is triggered.

Parameter description

0 specifies the left mouse button

1 specify the middle mouse button

2 specify the right mouse button

Middle mouse button code

FunctiononMouseDown (event) {

If (event.button==0) {

Console.log ("left mouse button!")

} elseif (event.button==2) {

Console.log ("right mouse button!")

} elseif (event.button==1) {

Console.log ("mouse wheel!")

}

}

Please click the mouse in the document. A message box will indicate which mouse button you clicked.

FunctionwhichButton (event) {

VarbtnNum=event.button

If (btnNum==2) {

Alert ("you clicked the right mouse!")

} elseif (btnNum==0) {

Alert ("you clicked the left mouse button!")

} elseif (btnNum==1) {

Alert ("you clicked the middle mouse button!")

} else {

Alert ("you clicked the" + btnNum+ "key, and I'm not sure its name.")

}

}

Thank you for your reading, the above is the content of "how to achieve the left and right mouse button and middle button event in JS". After the study of this article, I believe you have a deeper understanding of how to achieve the left and right mouse button and middle button event in JS, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Mouse event learning valid content button code element function parameter only name scene object namely attribute idea situation indication button Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei NVidia Apple Linux MySQL