如何滚动到溢出的Div中的元素? [英] How do I scroll to an element within an overflowed Div?

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

问题描述

我在div内有20个列表项,一次只能显示5个.滚动到第10项然后到第20项的好方法是什么?我知道所有物品的高度.

I have 20 list items inside of a div that can only show 5 at a time. What is a good way to scroll to item #10, and then item #20? I know the height of all the items.

scrollTo插件可以做到这一点,但是如果不真正了解它的源代码,就很难理解. 我不想使用此插件.

The scrollTo plugin does this, but its source is not super easy to understand without really getting into it. I don't want to use this plugin.

假设我有一个包含2个元素$parentDiv$innerListItem的函数,$innerListItem.offset().top$innerListItem.positon().top都没有为我提供$ parentDiv的正确scrollTop.

Let's say I have a function that takes 2 elements $parentDiv, $innerListItem, neither $innerListItem.offset().top nor $innerListItem.positon().top gives me the correct scrollTop for $parentDiv.

推荐答案

$innerListItem.position().top实际上相对于其第一个定位祖先的.scrollTop().因此,计算正确的$parentDiv.scrollTop()值的方法是先确定$parentDiv的位置.如果尚无明确的position,请使用position: relative.元素$innerListItem及其所有祖先($parentDiv)不需要具有明确的位置.现在,您可以使用以下命令滚动到$innerListItem:

The $innerListItem.position().top is actually relative to the .scrollTop() of its first positioned ancestor. So the way to calculate the correct $parentDiv.scrollTop() value is to begin by making sure that $parentDiv is positioned. If it doesn't already have an explicit position, use position: relative. The elements $innerListItem and all its ancestors up to $parentDiv need to have no explicit position. Now you can scroll to the $innerListItem with:

// Scroll to the top
$parentDiv.scrollTop($parentDiv.scrollTop() + $innerListItem.position().top);

// Scroll to the center
$parentDiv.scrollTop($parentDiv.scrollTop() + $innerListItem.position().top
    - $parentDiv.height()/2 + $innerListItem.height()/2);

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

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