2015-05-02 100 views
4

我試圖模擬在JavaScript在一個特定TextArea。 代碼:模擬輸入JavaScript

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的。爲什麼?

+0

[這裏](http://stackoverflow.com/questions/961532/firing-a-keyboard-event-in-javascript),[這裏](http://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-the-the-correct-key) – AvrilAlejandro

+0

@avrilalejandro感謝艾薇兒的支持,但是每個功能都沒有通過「回車」。我不明白。 –

回答

0

我認爲這是一個瀏覽器bug,因爲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); 
} 

另一種解決方案是KeyboardEvent Constructor。只要注意兼容性問題。

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

我編輯的代碼,但沒有改變。 感謝您的回答。 –

+0

@LucaLaiton您可以嘗試手動分配'keyboardEvent.which = 13;'而不是將鍵碼傳遞給'initMethod'。 – Lewis

+0

 function premi_enter() { var keyboardEvent = document.createEvent('KeyboardEvent'); delete keyboardEvent.which; keyboardEvent.which = 13; document.getElementById('text').dispatchEvent(keyboardEvent); }