how to make container scroll to element

本秂侑毒 提交于 2019-12-08 01:40:57

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/10437344/how-to-make-container-scroll-to-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!