模拟在 JavaScript 中输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30003774/
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-10-28 11:28:34  来源:igfitidea点击:

Simulate Enter In JavaScript

javascripthtmldom-eventskeyboard-eventsenter

提问by Luca Laiton

I try to simulate Enterin JavaScriptin a specific TextArea. This is my code:

我尝试模拟EnterJavaScript一个特定的TextArea。这是我的代码:

 function enter1() {
       var keyboardEvent = document.createEvent('KeyboardEvent'); 
       var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent'; 
       keyboardEvent[initMethod]('keydown', // event type : keydown, keyup, keypress
            true, // bubbles
            true, // cancelable
            window, // viewArg: should be window
            false, // ctrlKeyArg
            false, // altKeyArg
            false, // shiftKeyArg
            false, // metaKeyArg
            13, // keyCodeArg : unsigned long the virtual key code, else 0
            13 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
       );
       document.getElementById('text').dispatchEvent(keyboardEvent);
 }

TextArea:

TextArea

<textarea id="text"> </textarea>

When I call enter1(), it doesn't do anything in the TextArea. Why is this?

当我调用 enter1() 时,它在TextArea. 为什么是这样?

回答by Lewis

I think it's a browser bug since keyboardEvent.whichis unwritable. In order to fix it, you have to delete keyboardEvent.whichproperty before assigning the keycode.

我认为这是一个浏览器错误,因为它keyboardEvent.which是不可写的。为了修复它,您必须keyboardEvent.which在分配键码之前删除属性。

 function enter1() {
   var keyboardEvent = document.createEvent('KeyboardEvent');
   delete keyboardEvent.which;
   var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';
   keyboardEvent[initMethod](
     'keydown', // event type : keydown, keyup, keypress
     true, // bubbles
     true, // cancelable
     window, // viewArg: should be window
     false, // ctrlKeyArg
     false, // altKeyArg
     false, // shiftKeyArg
     false, // metaKeyArg
     13, // keyCodeArg : unsigned long the virtual key code, else 0
     13 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
   );
   document.getElementById('text').dispatchEvent(keyboardEvent);
 }

An alternative solution is KeyboardEvent Constructor. Just be careful with the compatibility issue.

另一种解决方案是KeyboardEvent Constructor。请注意兼容性问题。

 function enter1() {
   var keyboardEvent = new KeyboardEvent('keydown');
   delete keyboardEvent.which;
   keyboardEvent.which = 13;
   document.getElementById('text').dispatchEvent(keyboardEvent);
 }

回答by Dmytro Zasiadko

var textArea = document.getElementById('text');
function enter() {
    var keyboardEvent = new KeyboardEvent('keydown', {
        code: 'Enter',
        key: 'Enter',
        charKode: 13,
        keyCode: 13,
        view: window
    });

    textArea.dispatchEvent(keyboardEvent);
}

textArea.addEventListener('keydown', function (e) {
    console.log(e);
});
enter()
<!doctype html>
<html class="no-js" lang="">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>test</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>

<body>
    <textarea id="text"></textarea>
</body>

</html>

At this moment initKeyboardEventmethod is marked as deprecated. It is recommended to instantiate KeyboardEventdirectly and pass necessary data to constructor - link. See the browser compatibility section. At least it works in chrome and firefox.

此时initKeyboardEvent方法被标记为已弃用。建议KeyboardEvent直接实例化并将必要的数据传递给构造函数链接。请参阅浏览器兼容性部分。至少它适用于 chrome 和 firefox。