简体   繁体   中英

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. 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.

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.

  • When you click .1 , the offset distance to the top of the page is 300 .
  • Once .large which is now -300 is scrolled to that position, .1 offset becomes 0 , .2 becomes 300, .3 becomes 600 .
  • so you need to minus the offset of .large to get the real position.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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