Html 在没有 jquery 的情况下模拟按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17323279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:30:42  来源:igfitidea点击:

Simulate keypress without jquery

javascripthtml

提问by Mateus Viccari

I have an input field, where the user can write things. I want that, if the user press the key "1", to simulate another key press "F". So, if the user typer the character 1, in the field it will display 1f. How can i do it, without using jQuery?

我有一个输入字段,用户可以在其中写东西。我希望,如果用户按下键“1”,模拟另一个键按下“F”。因此,如果用户键入字符 1,则在该字段中将显示 1f。我该怎么做,而不使用 jQuery?

采纳答案by Carlos Bergen

var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent ("keypress", true, true, window,
                0, 0, 0, 0,
                13, 13); 
var canceled = !body.dispatchEvent(evt);

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/event.initKeyEvent

文档:https: //developer.mozilla.org/en-US/docs/Web/API/event.initKeyEvent

For Webkit-based browser the initialization might be a bit different

对于基于 Webkit 的浏览器,初始化可能有点不同

initKeyboardEvent(in DOMString typeArg, 
              in boolean canBubbleArg, 
              in boolean cancelableArg, 
              in views::AbstractView viewArg, 
              in DOMString keyIdentifierArg, 
              in unsigned long keyLocationArg, 
              in boolean ctrlKeyArg, 
              in boolean shiftKeyArg, 
              in boolean altKeyArg, 
              in boolean metaKeyArg, 
              in boolean altGraphKeyArg);