Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

jquery - How to scroll an item inside a scrollable div to the top

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Example:

var contactTopPosition = $("#contact_8967").position().top;
$("#contact-list-scroller").scrollTop(contactTopPosition);

or animated:

$("#contact-list-scroller").animate({scrollTop: contactTopPosition});

See jsfiddle: http://jsfiddle.net/5zf9s/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...