我正在用canvas和javascript做一个游戏。
当页面比屏幕长时(评论等)按向下箭头向下滚动页面,使游戏无法进行。
当玩家只想向下移动时,我可以做些什么来防止窗口滚动?
我猜对于Java游戏,这不是问题,只要用户点击游戏即可。
我尝试了来自How to disable page scrolling in FF with arrow keys的解决方案,但是我不能让它工作。
发布于 2021-08-19 18:04:55
这是为React重写的公认答案。
import { useEffect } from "react";
const usePreventKeyboardScrolling = () => {
const onKeyDown = (e) => {
if (
["Space", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].indexOf(
e.code
) > -1
) {
e.preventDefault();
}
};
useEffect(() => {
window.addEventListener("keydown", onKeyDown, false);
return () => window.removeEventListener("keydown", onKeyDown);
});
};
export { usePreventKeyboardScrolling };
https://stackoverflow.com/questions/8916620
复制相似问题