简体   繁体   English

为上/下箭头添加侦听器时以编程方式控制滚动条

[英]Controlling scrollbar programmatically when adding listeners for up/down arrows

https://jsfiddle.net/mhg0mzs3/ https://jsfiddle.net/mhg0mzs3/

I am trying to enable the user navigate through the list using up/down arrows. 我试图使用户使用上/下箭头浏览列表。 And I am having trouble controlling the scrollbar automatically. 而且我无法自动控制滚动条。 That is, understanding when and to what extent to move the scrollbar as the user reaches last visible elements. 也就是说,了解在用户到达最后一个可见元素时何时以及在何种程度上移动滚动条。

This question is most probably duplicate, but after spending some time, wansn't able to find analogue. 这个问题很可能是重复的,但是花了一些时间后,无法找到类似的问题。

 $(document).on('keydown', function(e) { if (e.which === 40) { e.preventDefault(); var $selected = $('.selected'); if ($selected.next().length !== 0) { $('li').removeClass('selected'); $selected.next().addClass('selected'); } } if (e.which === 38) { e.preventDefault(); var $selected = $('.selected'); if ($selected.prev().length !== 0) { $('li').removeClass('selected'); $selected.prev().addClass('selected'); } } }); 
 li { height: 100px; border: solid; } li.selected { background: red; } ul { overflow-y: auto; width: 150px; height: 300px; list-style-type: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>A</li> <li>B</li> <li class='selected'>C</li> <li>D</li> <li>E</li> <li>F</li> <li>G</li> <li>H</li> <li>I</li> <li>J</li> </ul> 

Rather than controlling the scrollbar itself, think of it as setting the scroll position of the list so that the selected item is in view. 与其控制滚动条本身,不如将其视为设置列表的滚动位置,以便查看选定的项目。

You can read the offsetTop property (or offset().top in JQuery) to find the top offset of the selected item, and then adjust slightly to centre it. 您可以阅读offsetTop属性(或JQuery中的offset().top )来找到所选项目的顶部偏移,然后对其进行稍微调整以使其居中。

This isn't perfect but it's close to what you want: 这不是完美的,但是接近您想要的:

https://jsfiddle.net/mhg0mzs3/2/ https://jsfiddle.net/mhg0mzs3/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM