[英]Focus on list item on down arrow press
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. 所以我将tabindex属性添加到li它正在获得焦点。 but problem is that it scrolling the div up with some random height that it out the selected li from div.
但问题是它以一些随机高度向上滚动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 JSFiddle first click item1
and then press arrow down it behaving same. 在这里我做了一个Demo JSFiddle首先点击
item1
然后按向下箭头它表现相同。
Elaborating on my comment 阐述我的评论
Set the container's scrollTop
to index of focused li
* li height
. 将容器的
scrollTop
设置index of focused li
* li height
index of focused li
。
return false
upon keydown to prevent normal browser scrolling of overflown parent. 在keydown时
return false
以防止溢出父级的正常浏览器滚动。
$('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/
Have you tried using anchor instead of tabindex? 你尝试过使用锚而不是tabindex吗? eg
例如
<li><a href="#"></li>
In my experience some browsers cannot handle the focus on tabindex correctly 根据我的经验,一些浏览器无法正确处理对tabindex的关注
我有一个这样的问题,并通过将包含div的CSS样式overflow
设置为none
或hidden
来解决它,具体取决于您的偏好。
添加.scrollTop()
以确保它居中或按您希望的方式放置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.