initKeyEvent 按键仅适用于 FireFox.需要一个跨浏览器的解决方案! [英] initKeyEvent keypress only works in FireFox. need a cross browser solution!

查看:13
本文介绍了initKeyEvent 按键仅适用于 FireFox.需要一个跨浏览器的解决方案!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

在 Firefox 中打开脚本,它正在运行.输入框内的空白处表示代码已生效.

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

然而,上面的代码在 Chrome、Safari、Opera 等中不起作用.

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?

推荐答案

对于基于 Webkit 的浏览器 (Safari/Chrome),事件初始化调用看起来应该有所不同(请参阅 https://bugs.webkit.org/show_bug.cgi?id=13368):

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

这篇关于initKeyEvent 按键仅适用于 FireFox.需要一个跨浏览器的解决方案!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆