Javascript 滚动到 li 元素 - jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4583476/
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
scrolling to li element - jquery
提问by Ran
i have a "ul" that contains lots of "li" (several hundred), the ul has a fixed hight of about 400px and the css property overflow:scroll, each li has the height of 40px so in every given moment there are no more then 10 visible li (the rest need to be scrolled to). how can i change the scroll position (using jquery) of the ul to a specific li?
我有一个包含很多“li”(数百个)的“ul”,ul 的固定高度约为 400px,css 属性溢出:scroll,每个 li 的高度为 40px,因此在每个给定时刻都没有超过 10 个可见 li(其余的需要滚动到)。如何将 ul 的滚动位置(使用 jquery)更改为特定的 li?
any thoughts?
有什么想法吗?
回答by lonesomeday
You need to do something like this:
你需要做这样的事情:
$('#yourUL').scrollTop($('#yourUL li:nth-child(14)').position().top);
If you want to animate it, do
如果你想动画它,做
$('#yourUL').animate({
scrollTop: $('#yourUL li:nth-child(14)').position().top
}, 'slow');
Obviously adjust 14
for different li
s.
显然14
要针对不同的li
s 进行调整。
回答by Suncat2000
I got close using @lonesomeday's answer, but I found that I had to calculate the relative position of the specific li
from the first li
because it changed depending on the current scroll position of the containing ul
.
我使用@lonesomeday 的答案接近了,但我发现我必须li
从第一个开始计算特定的相对位置,li
因为它根据包含ul
.
$('#yourUL').scrollTop($('#yourUL li:nth-child(14)').position().top - $('#yourUL li:first').position().top)
回答by Sarfraz
You can do like this:
你可以这样做:
$('html, body').animate({
scrollTop:$('#ulID li:eq(1)').offset().top
}, 1000);
You need to adjust value to eq
for specific li
or you can even customize the selector.
您需要将值调整eq
为特定的,li
或者您甚至可以自定义选择器。
回答by Darren
If anyone needs a vanilla JS version, the following is working well for me, the value of 50 is just so that I'm showing the whole item when I'm near the top of the list. You can adjust that.
如果有人需要 vanilla JS 版本,以下对我来说效果很好,50 的值只是为了当我靠近列表顶部时显示整个项目。你可以调整那个。
function updateListSelection(liID) {
var list = document.getElementById("id Tag Of The <UL> element"),
targetLi = document.getElementById(liID); // id tag of the <li> element
list.scrollTop = (targetLi.offsetTop - 50);
};