當我使用元素的KeyDown事件處理箭頭鍵(上/下/左/右)以將焦點設置到SELECT上時,獲得「聚焦」的SELECT似乎是接收一個「KeyUp」事件,它使得它選擇下一個/上一個OPTION(取決於你按下的箭頭)。它只發生在Firefox(測試3 & 4),其中IE8 & Chrome按預期工作(它們不會改變「聚焦」SELECT的值)。將焦點設置爲KeyDown和KeyUp事件之間的SELECT問題(Firefox bug?)
下面的代碼重現的問題(只要按下任何箭頭鍵,它會關注其他):
<!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>
感謝roberkules,這工作出色!謝謝你給我展示jsfiddle.net太棒了,真棒的網站! – Jocie 2011-05-25 08:48:50
不客氣,是的,jsfiddle似乎很棒,幾天前也偶然發現了它。想想,爲什麼我沒有想法:) – roberkules 2011-05-27 14:29:29