开发者

scrolling to li element - jquery

开发者 https://www.devze.com 2023-02-02 08:47 出处:网络
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 th

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开发者_Python百科 a specific li?

any thoughts?


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 lis.


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.

$('#yourUL').scrollTop($('#yourUL li:nth-child(14)').position().top - $('#yourUL li:first').position().top)


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.


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.

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);
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号