最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to make container scroll to element - Stack Overflow

programmeradmin1浏览0评论

I've got a container with a whole bunch of text in it and i want to auto-scroll to various elements in that container. I can animate the container using jQuery to scroll a certain distance nicely, however I am having a lot of trouble determining what that distance is.

Most of the hints I see remend using the .offset().top property to get that distance, but that isn't working in this case. Have a look at this jsfiddle for an example.

NOTE: the fiddle targets paragraph tags that are direct children of the container, but I don't want to rely on that. I want to be able to get the proper scroll distance for any elements, no matter how deeply nested they may be.

I've got a container with a whole bunch of text in it and i want to auto-scroll to various elements in that container. I can animate the container using jQuery to scroll a certain distance nicely, however I am having a lot of trouble determining what that distance is.

Most of the hints I see remend using the .offset().top property to get that distance, but that isn't working in this case. Have a look at this jsfiddle for an example.

NOTE: the fiddle targets paragraph tags that are direct children of the container, but I don't want to rely on that. I want to be able to get the proper scroll distance for any elements, no matter how deeply nested they may be.

Share asked May 3, 2012 at 18:33 doub1ejackdoub1ejack 11.2k20 gold badges77 silver badges130 bronze badges 1
  • How will you identify the target elements? By class, id, other... – Zuul Commented May 3, 2012 at 18:35
Add a ment  | 

2 Answers 2

Reset to default 6

Try using this:

var pOffset = $("#lipsum").scrollTop();
pOffset = pOffset + $("#lipsum p.active").position().top; 

.scrollTop() gives the current scroll position of the DIV, add the position of the P element to it and scrolling will be fine.

.offset() gets you the position of the element relative to the entire page.

What you need here is .position() that will get you the position of the element relative to the top of its containing element.

EDIT: Here it works with the updated JSFiddle

EDIT 2: I just noticed its not going to work without adding the scroll position. You'll need to add .scrollTop() from the containing div. Here is an updated JSFiddle. (It works this time)

发布评论

评论列表(0)

  1. 暂无评论