JavaScript 左右点击功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11925358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:46:55  来源:igfitidea点击:

JavaScript left and right click function

javascripthtml5-canvas

提问by JeremeiBou

This is for an HTML5 canvas game that I am making. In the game, there is a character that has a gun, he can shoot it and reload it. I would like the player to use the left mouse button for shooting and the right mouse button for reloading.

这是我正在制作的 HTML5 画布游戏。在游戏中,有一个角色拥有一把枪,他可以射击并重新装弹。我希望玩家使用鼠标左键进行射击,使用鼠标右键重新加载。

What I need is that when ever I click the left mouse button, a variable in my player object(Player1.isLeftClick) becomes true, and when I let go of the button the same variable becomes false. The same thing should also happen with the right mouse button, but with another variable(Player1.isRightClick). I also want it to be capable with all the most popular browsers(Chrome, Firefox, Explorer, etc.). I must also be in pure JavaScript with no libraries like jQuery!I already achieved this with keyboard events, but I need this with the mouse events.

我需要的是,当我单击鼠标左键时,我的播放器对象(Player1.isLeftClick)中的变量变为真,而当我松开按钮时,相同的变量变为假。鼠标右键也应该发生同样的事情,但使用另一个变量(Player1.isRightClick)。我还希望它能够支持所有最流行的浏览器(Chrome、Firefox、Explorer 等)。 我还必须使用纯 JavaScript,没有像 jQuery 这样的库!我已经通过键盘事件实现了这一点,但是我需要通过鼠标事件来实现这一点。

If it helps, I already have event handlers for keyboard up and down and mouse movement. These are made in the init function that initializes the game when the images are loaded.

如果有帮助,我已经有了用于键盘上下和鼠标移动的事件处理程序。这些是在加载图像时初始化游戏的 init 函数中完成的。

document.addEventListener('mousemove', mousePos, false);
document.addEventListener('keydown', checkKeyDown, false);
document.addEventListener('keyup', checkKeyUp, false); 

I also have variable called mie that is true if the used browser is Internet Explorer and false for other browsers.

我还有一个名为 mie 的变量,如果使用的浏览器是 Internet Explorer,则该变量为 true,而对于其他浏览器则为 false。

回答by Some Guy

You want to use the e.buttonproperty to check which mouse event was called. The value for the left mouse button being clicked is different in IE. Your code would look like this:

您想使用该e.button属性来检查调用了哪个鼠标事件。单击鼠标左键的值在 IE 中不同的。您的代码如下所示:

var left, right;
left = mie ? 1 : 0;
right = 2;

document.body.addEventListener('mousedown', function (e){
    if(e.button === left){
        Player1.isLeftClick = true;
    }
    else if(e.button === right){
        Player1.isRightClick = true;
    }
}, false);

document.body.addEventListener('mouseup', function (e){
    if(e.button === left){
        Player1.isLeftClick = false;
    }
    else if(e.button === right){
        Player1.isRightClick = false;
    }
}, false);

Demo

演示