在启用指针锁定 API 时,有什么方法可以识别右键单击事件(“contextmenu”)和滚动事件吗?我正在尝试创建一个基于浏览器的 3D 游戏,其中玩家将能够通过左键单击、右键单击、中键单击和滚动来执行不同的事件 - 当指针被锁定时。
index.html
<body><button id="lock">Start game</button</body>
app.js
$("#lock").on("click", function(e) {
lockPointer(); // invokes the requestPointerLock API
e.stopPropagation();
});
// this works perfectly
$("body").on("click", function(e) {
// do stuff on left click
});
// this does not work
$("body").on("contextmenu", function(e) {
// do stuff on right click
});
最佳答案
对于右键单击,您可以使用 mousedown
或 mouseup
事件,它与 requestPointerLock
配合使用
$('body').on('mousedown', function(e) {
if (e.which === 1) {
// left button
} else if (e.which === 2) {
// middle button
} else if (e.which === 3) {
// right button
}
});
对于滚动,您可以使用wheel
事件:
$('body').on('wheel', function(e) {
var dx = e.originalEvent.deltaX;
var dy = e.originalEvent.deltaY;
if (dy < 0) {
// scroll up
} else if (dy > 0) {
// scroll down
}
if (dx < 0) {
// scroll left (some mice support this)
} else if (dx > 0) {
// scroll right (some mice support this)
}
});
关于javascript - requestPointerLock期间识别鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212448/