Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

javascript - initKeyEvent keypress only works in FireFox. need a cross browser solution!

This is my code:

<script>
function f(){
var i=document.getElementById("i");
i.focus();
 var evt = document.createEvent("KeyboardEvent");
    evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 

0, 32);
    i.dispatchEvent(evt);
}
</script>
<body onload="f();">
<input id="i"/>
</body>

Open the script in firefox and it's working. The empty space within the input box shows that the code has worked.

However the above piece of code doesn't work in Chrome, Safari, Opera etc etc.

How do we modify the code above to make it work in these browsers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For Webkit-based browsers (Safari/Chrome), the event initialization call should look a bit differently (see https://bugs.webkit.org/show_bug.cgi?id=13368):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...