HTML阻止空格栏滚动页面 [英] HTML prevent space bar from scrolling page

查看:529
本文介绍了HTML阻止空格栏滚动页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是代码:

  window.onkeydown = function(e){
return!( e.keyCode == 32);
};

它完全符合我的要求,当按空格键时停止滚动页面。但是,它也会阻止用户在文本框中输入空格。



有没有办法阻止空格键滚动以及在键入时保留空格键功能?

解决方案

尝试检查 target 是body:



  window.addEventListener('keydown',function(e){if(e.keyCode == 32&&& e.target == document.body ){e.preventDefault();}});  

body {height:100000px; } < / pre>

 < input />< textarea><<< ; / textarea>  

$ b

演示


I'm using the code:

window.onkeydown = function(e) { 
    return !(e.keyCode == 32);
};

which does exactly what I want, stops the page from scrolling when the spacebar is pressed. However it also prevents the user from typing spaces in a textbox

Is there a way to prevent the spacebar-scroll as well as retain the spacebar functionality while typing?

解决方案

Try checking if target is the body:

window.addEventListener('keydown', function(e) {
  if(e.keyCode == 32 && e.target == document.body) {
    e.preventDefault();
  }
});

body { height: 100000px; }

<input />
<textarea></textarea>

Demo

这篇关于HTML阻止空格栏滚动页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆