如何基于jQuery实现英文、日文键盘布局通用的按键限制功能?
适配英文键盘的按键限制代码修改方案
原来的代码依赖keyCode(按键位置编码)判断输入,但不同键盘布局下,同一字符对应的按键位置会不同,导致在英文键盘上无法正常触发限制。解决思路是直接通过实际输入的字符来判断,使用e.key属性(该属性返回用户输入的具体字符,不受键盘布局影响),同时补充阻止默认输入行为的逻辑,避免用户在弹出提示后仍能输入禁止字符。
修改后的完整代码
$('input,textarea,div#editorId').on('keydown', function(e) { // 禁止反斜杠(\) if (e.key === '\\') { e.preventDefault(); // 阻止默认输入行为 Swal.fire({ type: "info", html: "BackSlash is not allowed", confirmButtonClass: "btn btn-success" }); } // 禁止双引号(")和单引号(') else if (e.key === '"' || e.key === "'") { e.preventDefault(); Swal.fire({ type: "info", html: "Double and Single Quotes are not allowed", confirmButtonClass: "btn btn-success" }); } // 禁止逗号(,) else if (e.key === ',') { e.preventDefault(); Swal.fire({ type: "info", html: "Comma is not allowed", confirmButtonClass: "btn btn-success" }); } });
核心修改说明
- 替换判断依据:用
e.key替代keyCode,直接匹配用户输入的字符,彻底摆脱键盘布局差异的影响 - 补充默认行为阻止:添加
e.preventDefault(),确保弹出提示的同时,禁止字符输入到目标元素中 - 简化逻辑结构:去掉复杂的shiftKey+keyCode组合判断,代码更易读、维护
内容的提问来源于stack exchange,提问作者Karthi A
相关产品推荐
相关产品推荐

