简体   繁体   English

如何使用溢出:自动对div的滚动位置进行动画处理?

[英]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测量从页面顶部到元素的距离。

  • When you click .1 , the offset distance to the top of the page is 300 . 单击.1 ,到页面顶部的偏移距离为300
  • Once .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
  • so you need to minus the offset of .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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM