Issue with setting focus on to a SELECT between KeyDown and KeyUp events (Firefox bug?)
When I handle the arrow keys (up/down/left/right) using the KeyDown event of an element to set focus onto a SELECT, the SELECT which gets "focused" seems开发者_开发技巧 the receive a "KeyUp" event which makes it select the next/previous OPTION (depending on which arrow you pressed).
It only happens in Firefox (tested in 3 & 4), where as IE8 & Chrome work as expected (they don't change the value of the "focused" SELECT).
The code below reproduces the issue (just press any arrow key and it will focus the other ):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>KeyUp Issue</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$("select")
.live("keydown", function(event)
{
switch (event.keyCode)
{
case 37: // left
case 38: // up
case 39: // right
case 40: // down
$(this).siblings().focus();
event.preventDefault();
break;
}
})
.live("keyup", function(event)
{
// This event handler makes absolutely no difference; it's still
// "broken" in Firefox and works fine in IE/Chrome without it.
switch (event.keyCode)
{
case 37: // left
case 38: // up
case 39: // right
case 40: // down
event.preventDefault();
break;
}
})
.live("keypress", function(event)
{
// This event handler makes absolutely no difference; it's still
// "broken" in Firefox and works fine in IE/Chrome without it.
switch (event.keyCode)
{
case 37: // left
case 38: // up
case 39: // right
case 40: // down
event.preventDefault();
break;
}
});
</script>
<select id="select1">
<option>One</option>
<option>Two</option>
<option>Three</option>
<option>Four</option>
</select>
<select id="select2">
<option>One</option>
<option>Two</option>
<option>Three</option>
<option>Four</option>
</select>
</body>
</html>
The keypress event is the one which would need to be canceled, but Firefox ignores preventDefault() in this scenario. So the solution is to blur the current dropdown, let the keypress event fire on the document and set the focus to the new dropdown via timeout.
Demo at http://jsfiddle.net/roberkules/3vA53/
The problem you are facing is the key press right ?
http://www.mkyong.com/jquery/jquery-keyboard-events-example/
should help you understand why! Something to do with case sensitivity characters I think.
精彩评论