And*_*rea 15 javascript keyboard
我需要检测刚按下的键是否是可打印的键,如字符,可能带有重音,数字,空格,标点符号等,或者是不可打印的键,如ENTER,TAB或DELETE.
有没有一种可靠的方法在Javascript中执行此操作,除了列出所有不可打印的键并希望不要忘记一些?
Lew*_*wis 22
幸运的是,在现代浏览器中,此任务更容易.您现在可以使用它KeyboardEvent.key
来检测可打印键的长度.
test.onkeydown = e => {
let isPrintableKey = e.key.length === 1;
alert(`Key '${e.key}' is printable: ${isPrintableKey}`);
}
Run Code Online (Sandbox Code Playgroud)
<input id="test">
Run Code Online (Sandbox Code Playgroud)
除此之外,你还可以从列表中检测到任何其他按键一样Enter
,Delete
,Backspace
,Tab
,等.
这种方法是非常可靠的,只是因为不像event.which
,event.key
已经标准化.
Tim*_*own 16
我昨天回答了类似的问题.请注意,您必须将该keypress
事件用于任何与字符相关的事件; keydown
不会这样做.
Enter顺便提一下,我认为这是可打印的,而且这个函数认为它是可行的.如果您不同意,可以修改它以过滤出具有设置为13的事件which
或keyCode
属性的按键.
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (isCharacterKeyPress(evt)) {
// Do your stuff here
alert("Character!");
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7514 次 |
最近记录: |