![](/img/trans.png)
[英]How to auto scroll (animate) a <div> with text, with overflow set to auto or scroll?
[英]How to animate scroll position of div with overflow: auto?
我正在尝试创建一个函数,该函数将给定的div或body滚动到其中的元素位置。 当前看起来像:
function scrollTo($elem, offset, delay, $context){
delay = delay || 800;
offset = offset || 0;
$context = $context || $('html, body');
$context.animate({
scrollTop: $elem.offset().top-offset
}, delay);
}
它在主体上运行良好,但是,当我给它$ context时,第一个调用按预期运行,但是所有连续调用都滚动到错误的位置。
为什么会出现这种现象以及如何解决? 小提琴
offset().top
测量从页面顶部到元素的距离。
.1
,到页面顶部的偏移距离为300
。 -300
.large
滚动到该位置, .1
偏移量变为0
, .2
变为300, .3
变为600
。 .large
的偏移量才能获得真实位置。 码
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);
}
这是jsfiddle https://jsfiddle.net/a8jc5q6r/4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.