[英]HTML prevent space bar from scrolling page
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? 有没有办法阻止空格键滚动以及在键入时保留空格键功能?
You could look into e.target
and if it is the body you return false
. 您可以查看
e.target
,如果它是正文,则返回false
。
window.onkeydown = function(e) {
return !(e.keyCode == 32 && e.target == document.body);
};
window.onkeydown = function(e) {
e = e || window.event; //normalize the evebnt for IE
var target = e.srcElement || e.target; //Get the element that event was triggered on
var tagName = target.tagName; //get the tag name of the element [could also just compare elements]
return !(tagName==="BODY" && e.keyCode == 32); //see if it was body and space
};
You can check the target of the event, and only run your code if it's not a 'type-able' element. 您可以检查事件的目标,只有在不是“可输入”元素时才运行代码。 For example:
例如:
window.onkeydown = function(e) {
var elem = e.target.nodename;
if( elem !== 'TEXTAREA' && elem != 'INPUT' ) {
return !(e.keyCode == 32);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.