6

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

4

1 回答 1

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

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

对于基于 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);
于 2013-06-26T14:49:51.493 回答