取消HTML中的keydown [英] Cancel the keydown in HTML

查看:148
本文介绍了取消HTML中的keydown的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何取消键盘上特定键的 keydown ,例如(空格,回车键和箭头)在HTML页面中。

解决方案

如果您只对您提到的示例键感兴趣, c> keydown 事件将会执行,除了较早的Blink版本的Opera(至少包括版本12),您需要取消按键事件。在 keydown 事件中比 keypress 事件更可靠地识别不可打印的键,因此以下内容使用变量设置在 keydown 处理程序中,以告诉 keypress 处理程序是否禁止默认行为。

  var cancelKeypress = false; 

document.onkeydown = function(evt){
evt = evt || window.event;
cancelKeypress = / ^(13 | 32 | 37 | 38 | 39 | 40)$ /。test(+ evt.keyCode);
if(cancelKeypress){
return false;
}
};
$ b $ *对于Opera * /
document.onkeypress = function(evt){
if(cancelKeypress){
return false;
}
};


How can I cancel the keydown of a specific key on the keyboard, for example(space, enter and arrows) in an HTML page.

解决方案

If you're only interested in the example keys you mentioned, the keydown event will do, except for older, pre-Blink versions of Opera (up to and including version 12, at least) where you'll need to cancel the keypress event. It's much easier to reliably identify non-printable keys in the keydown event than the keypress event, so the following uses a variable to set in the keydown handler to tell the keypress handler whether or not to suppress the default behaviour.

var cancelKeypress = false;

document.onkeydown = function(evt) {
    evt = evt || window.event;
    cancelKeypress = /^(13|32|37|38|39|40)$/.test("" + evt.keyCode);
    if (cancelKeypress) {
        return false;
    }
};

/* For Opera */
document.onkeypress = function(evt) {
    if (cancelKeypress) {
        return false;
    }
};

这篇关于取消HTML中的keydown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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