按下向下箭头按下列表项

Zah*_*med 15 javascript jquery focus html-lists

我正在创建一个自定义的自动建议框,我需要li按下箭头按下的项目.

所以我将tabindex属性添加到li它正在获得焦点.但问题是它以一些随机高度向上滚动div,它从div中选择了li.

在此输入图像描述

向下箭头键后:

在此输入图像描述

按下一些向下箭头键后:

在此输入图像描述

之后它会离开屏幕,而鼠标按下则表现完美.

在这里我 首先点击了一个Demo JSFiddleitem1,然后按向下箭头它表现相同.

Dav*_*oli 16

阐述我的评论

将容器设置scrollTopindex of focused li*li height.

return false 在keydown上阻止正常浏览器滚动溢出的父级.

$('div.container').on('focus', 'li', function() {
    var $this = $(this);
    $this.addClass('active').siblings().removeClass();
    $this.closest('div.container').scrollTop($this.index() * $this.outerHeight());
}).on('keydown', 'li', function(e) {
    var $this = $(this);
    if (e.keyCode === 40) {        
        $this.next().focus();
        return false;
    } else if (e.keyCode === 38) {        
        $this.prev().focus();
        return false;
    }
}).find('li').first().focus();
Run Code Online (Sandbox Code Playgroud)

jsfiddle http://jsfiddle.net/38zR3/42/