Joc*_*cie 2 jquery select focus
当我使用元素的KeyDown事件处理箭头键(向上/向下/向左/向右)将焦点设置到SELECT时,获得"聚焦"的SELECT似乎接收到一个"KeyUp"事件,使其选择下一个/ previous OPTION(取决于您按下的箭头).
它只发生在Firefox(在3和4中测试),其中IE8和Chrome按预期工作(它们不会改变"聚焦"SELECT的值).
下面的代码重现了问题(只需按任意箭头键,它将聚焦另一个):
<!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>
Run Code Online (Sandbox Code Playgroud)
按键事件是需要取消的事件,但Firefox在此方案中忽略了preventDefault().因此解决方案是模糊当前下拉列表,让按键事件触发文档并通过超时将焦点设置为新的下拉列表.
演示http://jsfiddle.net/roberkules/3vA53/