本文介绍了模拟在JavaScript中输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在特定的TextArea中模拟JavaScript中的Enter.这是我的代码:

I try to simulate Enter in JavaScript in a specific TextArea.This is my code:

 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 id="text"> </textarea>

当我调用enter1()时,它在TextArea中没有任何作用.为什么会这样?

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

推荐答案

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

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

 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);
 }

另一种解决方案是 KeyboardEvent构造函数.请注意兼容性问题.

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

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

这篇关于模拟在JavaScript中输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 01:56