[英]How to animate scroll position of div with overflow: auto?
I'm trying to create a function which scrolls given div or body to an element's location within. 我正在尝试创建一个函数,该函数将给定的div或body滚动到其中的元素位置。 Currently it looks like: 当前看起来像:
function scrollTo($elem, offset, delay, $context){
delay = delay || 800;
offset = offset || 0;
$context = $context || $('html, body');
$context.animate({
scrollTop: $elem.offset().top-offset
}, delay);
}
It works fine on body, however, when I give it $context the first call works as intended, but all the consecutive calls are scrolling to a wrong position. 它在主体上运行良好,但是,当我给它$ context时,第一个调用按预期运行,但是所有连续调用都滚动到错误的位置。
Why is this behavior and how to fix it? 为什么会出现这种现象以及如何解决? FIDDLE 小提琴
The offset().top
measures the distance from the top of the page to the element. offset().top
测量从页面顶部到元素的距离。
.1
, the offset distance to the top of the page is 300
. 单击.1
,到页面顶部的偏移距离为300
。 .large
which is now -300
is scrolled to that position, .1
offset becomes 0
, .2
becomes 300, .3
becomes 600
. 一旦将现在-300
.large
滚动到该位置, .1
偏移量变为0
, .2
变为300, .3
变为600
。 .large
to get the real position. 因此您需要减去.large
的偏移量才能获得真实位置。 Code 码
function scrollTo($elem, offset, delay, $context){
delay = delay || 800;
offset = offset || 0;
$context = $context || $('html, body');
var a = $context.find('.large'); //need this
$context.animate({
scrollTop: $elem.offset().top - a.offset().top
}, delay);
}
Here is the jsfiddle https://jsfiddle.net/a8jc5q6r/4/ 这是jsfiddle https://jsfiddle.net/a8jc5q6r/4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.