[HTML DOM]全局按键事件
最近在建设着自己的网站的时候,想学学Javascript的按键事件,遇到很奇怪的问题:
// JavaScript Document
function move(event) {
var obj = document.getElementById('sprite');
if(event.keyCode == 37) { //left
obj.style.left = parseInt(obj.style.left) - 5 + 'px';
}
if(event.keyCode == 39) { //right
obj.style.left = parseInt(obj.style.left) + 5 + 'px';
}
alert(event);
}
window.onload = function() {
var x = document.createElement('div');
x.id = 'sprite';
x.style.position = 'absolute';
x.style.left = '0px';
x.style.top = '0px';
x.innerHTML = 'Hello,world!';
document.body.appendChild(x);
document.body.style.width = '500px';
document.body.style.height = '500px';
document.body.onkeyup = function(e) {
if(e != null) {
move(e);
} else {
move(event);
}
}
}
如果在IE下浏览,代码可用,id为sprite的标签可以移动。但Firefox却不行,但没有报错。难道Firefox不支持onkeyup?于是上http://www.w3school.com.cn/上查了下,应该是支持的。但为什么Firefox得不到预想效果呢?
于是上w3school的在线编辑器,试验了一下代码:
<html>
<head>
<script type="text/javascript">
function whichButton(event)
{
alert(document.body.onkeyup);
}
</script>
</head>
<body onkeyup="whichButton(event)">
<p onkeyup="5">
<b>Note:</b> Make sure the right frame has focus when trying this example!</p>
<p>Press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p>
</body>
</html>
(内容已经改了,那些文字没什么意思)IE下弹出的窗口的内容是onkeyup函数的内容,而在Firefox下却是undefine……无奈ing。难道Firefox不支持吗?
后来改了下代码,就是把代码段1的
alert(document.body.onkeyup);
改为
alert(document.onkeyup);
勉强可以实现,但为什么在body里就不能加onkeyup事件呢?
评论 (0)