Javascript 按键输入不工作?
我有一些代码可以在按键时运行函数:Javascript 按键输入不工作?,javascript,google-chrome,Javascript,Google Chrome,我有一些代码可以在按键时运行函数: document.onkeypress=function(e) { var e=window.event || e var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit. var unicode=evtobj.charC
document.onkeypress=function(e)
{
var e=window.event || e
var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
if (unicode == 39)
{
Rotate();
}
}
function Rotate()
{
myDiv.setAttribute('style', '-moz-transform:rotate(' + rotationAmount + 'deg); -o-transform:rotate(' + rotationAmount + 'deg);-webkit-transform:rotate(' + rotationAmount + 'deg);-ms-transform:rotate(' + rotationAmount + 'deg)');
}
不管出于什么原因,按键输入在Firefox中起作用,但在Chrome中不起作用。当我在Chrome中按下一个键时,什么也没发生。我知道Rotate()函数在Chrome中工作,因为如果我在不同的条件下调用它,它运行时不会出现问题。您似乎在检测右箭头键。对于此按键和任何其他不可打印的按键,您应该使用
keydown
事件,而只使用keyCode
属性,该属性适用于所有主要浏览器。您还可以简化事件代码:
document.onkeydown = function(e)
{
e = e || window.event;
if (e.keyCode == 39)
{
Rotate();
}
};
您的
evtobj
变量似乎太棒了。您可以只引用您的e
。