Javascript 通过java脚本禁用按键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8269274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable a key press event through java script
提问by Arun
i need to disable shift keypress event in my site by using javascript or any other method. Below is my code:
我需要使用 javascript 或任何其他方法在我的网站中禁用 shift keypress 事件。下面是我的代码:
$(document).ready(function() {
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) {
keycode = window.event.keyCode;
}
else if (e) {
keycode = e.which;
}
//alert(keycode);
if (keycode == 16) {
alert(keycode);
return false;
}
}
});
回答by Poelinca Dorin
// bind an event listener to the keydown event on the window
window.addEventListener('keydown', function (event) {
// if the keyCode is 16 ( shift key was pressed )
if (event.keyCode === 16) {
// prevent default behaviour
event.preventDefault();
return false;
}
});
回答by krolik
http://api.jquery.com/keypress/
http://api.jquery.com/keypress/
In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.
此外,修饰键(例如 Shift)会触发 keydown 事件,但不会触发 keypress 事件。
Try this
尝试这个
$('#target').keydown(function(event) {
if (event.shiftKey) {
event.preventDefault();
}
}
回答by Yuriy Rozhovetskiy
document.onkeydown = function (e) {
var e = e || event;
if (e.shiftKey === true) {
return false;
}
};