【问题标题】:Focus on list item on down arrow press在向下箭头按下时关注列表项
【发布时间】:2013-04-02 11:41:45
【问题描述】:

我正在创建一个自定义自动建议框,我需要在按下箭头时继续 li 项目。

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

在箭头键之后:

在按下箭头键后:

然后它会在鼠标按下时退出屏幕。

在这里我做了一个Demo JSFiddle 首先点击item1,然后按箭头向下它的行为相同。

【问题讨论】:

标签: javascript jquery focus html-lists


【解决方案1】:

详细说明我的评论

将容器的scrollTop 设置为index 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();

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

【讨论】:

    【解决方案2】:

    您是否尝试过使用锚点而不是 tabindex?例如

    <li><a href="#"></li>
    

    根据我的经验,有些浏览器无法正确处理 tabindex 的焦点

    【讨论】:

      【解决方案3】:

      我曾经遇到过这样的问题,并通过将包含 div 的 CSS 样式 overflow 设置为 nonehidden 来解决它,具体取决于您的喜好。

      【讨论】:

      • 谢谢...工作正常,但无法更改显示滚动的要求。
      【解决方案4】:

      添加.scrollTop() 以确保它居中或您想要的样子。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多