如何将可滚动div中的项目滚动到顶部 [英] How to scroll an item inside a scrollable div to the top
问题描述
我有一个#contact-list-scroller div,它可以在页面中滚动.根据contact_XXXX ID,我希望下注#contact-list-scroller滚动位置以确保contact_XXX项位于页面顶部.
I have a #contact-list-scroller div that scrolls in the page. Based on a contact_XXXX ID I'd like the #contact-list-scroller scroll position to bet set to make sure the contact_XXX item is at the top of the page.
<div id="contact-list-scroller">
<div id="contact_8965">stuff</div>
<div id="contact_8966">stuff</div>
<div id="contact_8967">stuff</div>
<div id="contact_8968">stuff</div>
<div id="contact_8969">stuff</div>
.....
</div>
这是我到目前为止所拥有的:
Here's what I have so far:
$('#contact-list-scroller').scrollTop($('#contact_' + id).scrollTop());
但这只是滚动到顶部.有想法吗?谢谢
But that is just scrolling to the top. Ideas? Thanks
推荐答案
我认为您需要 position() .top .因为position()返回的值是相对于其父级的(与offset()不同),所以它使您的代码更灵活.如果您更改父容器的位置,则代码不会中断.
I think you'll need position().top. Because the values returned by position() are relative to its parent (unlike offset()), it makes your code more flexible. If you change the position of your parent container your code won't break.
示例:
var contactTopPosition = $("#contact_8967").position().top;
$("#contact-list-scroller").scrollTop(contactTopPosition);
或动画:
$("#contact-list-scroller").animate({scrollTop: contactTopPosition});
请参阅jsfiddle: http://jsfiddle.net/5zf9s/
See jsfiddle: http://jsfiddle.net/5zf9s/
这篇关于如何将可滚动div中的项目滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!