简体   繁体   中英

Prevent arrow key from scrolling with keydown event

I have a game captured inside of an Iframe within my body. 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();
  }
});

您可以根据情况(例如玩游戏时)应用按键侦听器并停止特定输入的正常功能

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM