Javascript keydown listener not working after click
hoping someone can help me with this. Im making a game in html5/javascript and I want the user to be able to move the map around with the arrow keys, and carry out some code when the player clicks on the canvas. I have all that working fine but for some reason sometimes when the user clicks the canvas, the keydown l开发者_JAVA技巧istener stops working unless they click outside of the canvas again. I've tried to google it and it seems to be i want to set up delegation to fix it, but im having trouble getting it to work. Here's my current code:
$(window).keydown(function(event){keyDown(event);});
$("#game").click(function(e){
var x = e.pageX - $(this).offset().left;
var y = e.pageY - $(this).offset().top;
alert(x+" "+y);
});
Any help would be greatly appreciated.
I guess your tag is not got the event because it hasn't a focus?
Here a solution with work in my environment. That to make a div tag is focusable pass it tabindex="0" attribute.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<script type="text/javascript">
function xxx() {
var div = document.getElementById('x');
div.focus();
}
function keyd(e) {
alert("DDDDDDDD" + e );
}
</script>
</head>
<body onload="xxx();">
<div tabindex="0" id='x' onkeydown="keyd(event);" style="background-color: green; width: 100px; height: 100px;">
</div>
</body>
</html>
I stuck your code in jsFiddle and it appears to work every time: http://jsfiddle.net/ianoxley/fb26Y/
Just wondering which browser / OS you're using? And what happens in your keyDown
function called in your keydown
event handler?
精彩评论