【发布时间】:2012-02-20 00:44:29
【问题描述】:
我正在尝试使用向上/向下箭头键使列表可导航 - 这有效,但按下这些键会导致窗口滚动,这非常烦人。因此,我想在此框获得焦点时使用箭头键禁用页面移动。
我试过了:
$('.selectionList').focus(function(event){
$(document).keydown(function(e) {
return false;
});
});
$('.selectionList').blur(function(event){
$(document).keydown(function(e) {
return true;
});
});
但是重新启用这些键不起作用,如果没有滚动条,页面将无法滚动。我找到了可以使用的this,但这会永久禁用这些密钥,这是我不希望发生的。
$('.selectionList').keyup() 事件如下:
$('.selectionList').keyup(function(event){
if (event.keyCode == 13) //enter
{
$('.listNameBox a').click();
}
else
{
if ((event.keyCode == 38) && ($(this).children('li:eq(' + ($('.selectionList li.selected').index() - 1) + ')').length > 0)) //up
{
selectListItem($(this).children('li:eq(' + ($('.selectionList li.selected').index() - 1) + ')'));
}
else if ((event.keyCode == 40) && ($(this).children('li:eq(' + ($('.selectionList li.selected').index() + 1) + ')').length > 0)) //down
{
selectListItem($(this).children('li:eq(' + ($('.selectionList li.selected').index() + 1) + ')'));
};
}
});
任何帮助将不胜感激。
【问题讨论】:
-
您的
.blur()处理程序没有替换以前的 keydown 处理程序,它正在添加另一个。尝试在您的.blur()处理程序中使用$(document).off('keydown')或$(document).unbind('keydown')来删除以前的 keydown 处理程序。 -
谢谢 $('.selectionList').focus(function(event){ $(document).keydown(function(e) { return false; }); }); $('.selectionList').blur(function(event){ $(document).unbind('keydown'); });似乎工作
-
酷。我添加了我的评论作为答案。 (我最初没有这样做,因为当时我没有时间分析您的 keyup 功能以查看它是否是问题的一部分,但是既然您说使用
.unbind()修复了一些问题......)