我有一个文本区域,应该只接受选定的字符
问题描述:
文本区域应该只接受数字,逗号,方向键(键盘),空格,Ctrl + c,Ctrl + v,Ctrl + x,Ctrl + a,它应该仅限于JavaScript。 以下是我的代码:我有一个文本区域,应该只接受选定的字符
<textarea onkeypress=' return validateKey(event)'></textarea>
<body>
<script type="text/javascript">
function validateKey(e){
var key= e.keyCode ? e.keyCode : e.charCode;
console.log(key);
if(key>47 && key <=57 || key>36 && key <=40 || key===44|| key===32 ||x|| key===8 || x|| key ===118 || key==99 || key === 120){
return true;
}
return false;
}
</script>
</body>
它正常工作与Chrome,但在Firefox,它采用相同的键码为 'a' 和CTRL + A或CMD + A键(Mac)等开始剪切,粘贴,复制。
有没有什么办法可以对待ctrl + a,'a'是两个不同的字符。
答
只需在您的其他if
以外添加if (!e.ctrlKey)
。如果控制键被按下,这将阻止它运行。
+0
不幸的是,我一直在获取e.ctrlKey为false! –
答
我已经找到了道路,此验证
<!DOCTYPE html>
<html>
<head>
\t <title>Task</title>
</head>
<body>
\t <textarea style="width: 300px;height: 100px" onkeypress=' return validateKey(event)'></textarea>
\t <script type="text/javascript">
\t \t function validateKey(e) {
var key = e.keyCode ? e.keyCode : e.charCode;
console.log(key);
if (key > 47 && key <= 57||(key > 36 && key <= 40) && !e.shiftKey || key === 44 || key == 17 || key === 32 || key === 8 || (key == 97 && e.ctrlKey) || (key == 120 && e.ctrlKey) || (key == 99 && e.ctrlKey) || (key == 118 && e.ctrlKey) || e.metaKey) {
return true;
}
return false;
}
\t </script>
</body>
</html>
的可能的复制[如何检测键盘修饰符(Ctrl或Shift)通过JavaScript(https://*.com/问题/ 13539493/how-to-detect-keyboard-modifier-ctrl-or-shift-through-javascript) –
不要。只要确保'this.value.match(/^[0-9,] * $ /)'通过。 –
e.ctrlKey与cmd + ctrl事件相同吗? –