javascript, simulate keyboard events, work on chrome(webkit)

白昼怎懂夜的黑 提交于 2019-12-18 05:18:29

问题


in FF, i've used this code:


if (keyCount == lineLimit) {
    // method in FF, no Chrome
    var mock = document.createEvent("KeyboardEvent"); // or KeysEvent
    mock.initKeyEvent("keypress",true,true,null,false,false,false,false,14,0);
    var x = document.getElementById('InputCategory');
    // rise height before Enter
    $(this).height(div_height + font_height + offset_height);
    // mock Enter
    x.dispatchEvent(mock);
    // init keyCount
    keyCount = 0;
}

it works, but could not be effective on webkit-based browsers like chrome.

so i asked google and found keyboard event is one of the DOM Level 3 events,here is an aticle: http://www.w3.org/TR/DOM-Level-3-Events/

then i knew /* initKeyboardEvent / is not supported on chrome & safari, / initUIEvent */ i've tried, it didn't work also.

Do virtual keyboard events reall can be simulated on chrome ? plesase help me :)


回答1:


This works, but it's not generating a keypress-event, rather a text-insert event.

var te = document.createEvent('TextEvent');
te.initTextEvent('textInput', true, true, window, 'test');
<element>.dispatchEvent(te);

That inserts the word 'test' at the end of the input (in your case you'd probably replace that by \n.



来源:https://stackoverflow.com/questions/4846687/javascript-simulate-keyboard-events-work-on-chromewebkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!