[英]How to prevent page from scrolling when a JQuery button is focused and space-bar is pressed
[英]HTML prevent space bar from scrolling page
我正在使用代碼:
window.onkeydown = function(e) {
return !(e.keyCode == 32);
};
這正是我想要的,當按下空格鍵時停止頁面滾動。 但是,它還會阻止用戶在文本框中鍵入空格
有沒有辦法阻止空格鍵滾動以及在鍵入時保留空格鍵功能?
您可以查看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
};
您可以檢查事件的目標,只有在不是“可輸入”元素時才運行代碼。 例如:
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.