如何使容器滚动到元素 [英] how to make container scroll to element

查看:95
本文介绍了如何使容器滚动到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大量文本的容器,我想自动滚动到该容器中的各种元素。我可以使用jQuery为容器设置动画,以便很好地滚动一定距离,但是我确定距离是多少。

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.

我看到的大多数提示建议使用.offset(。。top属性来获取该距离,但在这种情况下这不起作用。 请看一下这个jsfiddle的例子。

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.

推荐答案

尝试使用这个:

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

.scrollTop()给出当前滚动条DIV的位置,将P元素的位置添加到它,滚动就可以了。

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

这篇关于如何使容器滚动到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆