jQuery 按向下箭头键专注于列表项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15929117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Focus on list item on down arrow press
提问by Zaheer Ahmed
I am creating a custom auto suggest-box I need to move on li
items on arrow down press.
我正在创建一个自定义的自动建议框,我需要li
在按下箭头时移动项目。
so I added tabindex attribute to li it is getting focus. but problem is that it scrolling the div up with some random height that it out the selected li from div.
所以我向 li 添加了 tabindex 属性,它正在获得焦点。但问题是它以一些随机高度向上滚动 div,它从 div 中选择了 li。
after arrow down key:
向下箭头键后:
and after some arrow-down key press:
在按下一些箭头键后:
and after that it goes out of screen while mouse down behave perfectly.
之后它会退出屏幕,而鼠标按下时表现完美。
Here I made a Demo JSFiddlefirst click item1
and then press arrow down it behaving same.
在这里,我
首先点击了一个演示 JSFiddleitem1
,然后按下箭头,它的行为相同。
采纳答案by David Fregoli
Elaborating on my comment
详细说明我的评论
Set the container's scrollTop
to index of focused li
* li height
.
将容器设置scrollTop
为index of focused li
* li height
。
return false
upon keydown to prevent normal browser scrolling of overflown parent.
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/
jsfiddle http://jsfiddle.net/38zR3/42/
回答by CevenNome
Have you tried using anchor instead of tabindex? e.g
您是否尝试过使用锚点而不是 tabindex?例如
<li><a href="#"></li>
In my experience some browsers cannot handle the focus on tabindex correctly
根据我的经验,某些浏览器无法正确处理 tabindex 的焦点
回答by Cy Pangilinan
I had a problem like that once and solved it by setting the CSS style overflow
of the containing div to none
or hidden
depending on your preference.
我曾经遇到过这样的问题,并通过将overflow
包含 div的 CSS 样式设置为none
或hidden
根据您的喜好来解决它。
回答by Mihai Stancu
Add a .scrollTop()
to make sure it is either centered or how you want it to be.
添加一个.scrollTop()
以确保它居中或您想要的方式。