滚动列表项使其可见? [英] Scroll a list item such that it becomes visible?
本文介绍了滚动列表项使其可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含一堆元素的列表.通常,需要滚动条才能显示所有内容.我在运行时将项目添加到列表中.有什么方法可以滚动特定的列表元素,以确保其可见?:
I have a list with a bunch of elements. Usually a scrollbar is required to show them all. I add items to the list at runtime. Is there some way to scroll a particular list element such that it is ensured to be visible?:
<ul id='parent'>
<li>blah</li>
...
<li id='nthItem'>blah</li>
</ul>
$('#parent').scrollChildToVisible('nthItem');
类似的东西吗?
谢谢
推荐答案
要滚动到某个元素,可以使用 .animate() .
To scroll to an element you can use .animate().
这是滚动到jQuery选择器(如ID)的函数的示例:
Here's an example of a function that scrolls to a jQuery selector (like an ID):
// This is a function that scrolls to $(selector)
function goToByScroll(selector){
// Scroll
$('html,body').animate({
scrollTop: $(selector).offset().top},
'slow');
}
您可以在必要时触发此功能.例如,在添加有问题的元素之后:
You can trigger this function whenever it is necessary. For example right after you've added the element in question:
// Append item
$("#parent").append("<li id='nthItem'>blah</li>");
// Scroll to item using function above.
goToByScroll("#nthItem");
jsFiddle示例
最后,要在jQuery中选择id
,请使用
$("#nthItem") // correct for an ID
不是
$("nthItem") // incorrect
这篇关于滚动列表项使其可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文