[英]Prevent arrow key from scrolling with keydown event
I have a game captured inside of an Iframe within my body. 我体内的iframe内有一个游戏。 Problem is, the entire page scrolls when the arrow keys are pressed.
问题是,当按下箭头键时,整个页面都会滚动。 How can I prevent this?
我该如何预防? I don't want to disable scrolling with the arrow keys alogether, only when the game is being played.
我不想禁用箭头键,除非正在玩游戏。
Use a variable as a flag and add an event listener to see if that flag is present, if so, disable the key: Live demo here (click). 将变量用作标志,并添加事件侦听器以查看该标志是否存在,如果存在,请禁用该键: 在此处进行实时演示(单击)。
var flag = true;
document.body.addEventListener('keydown', function(e) {
var badKey = 40; //down array keyCode
if (flag && e.keyCode === badKey) {
e.preventDefault();
}
});
您可以根据情况(例如玩游戏时)应用按键侦听器并停止特定输入的正常功能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.