我正在使用'keydown'事件替换输入文本框中键入的特定字符。
当我使用时:
document.getElementById('inputText').onkeydown = handleInputTextKeydown;
Run Code Online (Sandbox Code Playgroud)
或等效的JQuery:
$('#inputText').on('keydown',handleInputTextKeydown);
Run Code Online (Sandbox Code Playgroud)
我得到了预期的结果-例如,Shift + i键显示为“í”。
但是,如果我使用addEventListner作为keydown钩子:
var tb = document.getElementById('inputText');
tb.addEventListener('keydown', handleInputTextKeydown, false);
Run Code Online (Sandbox Code Playgroud)
输入文本框同时显示我的替代字符(í)和“ I”(大写i)“íI”。
为什么addEventListener方法不同于两个“ onkeydown”钩子?
我的测试浏览器是IE 11。
顺便说一句:我正在使用另一种stackoverflow帖子中的keydown文本替换方法的变体:
newKey = keyMap[keyPressed]; // Look for this key in our list of accented key shortcuts
if (newKey === undefined) {
return true; // Not in our list, let it bubble up as is
} else {
var oldValue, start, end;
oldValue = this.value; // Insert the updated key into the correct position within the edit …Run Code Online (Sandbox Code Playgroud)