Scrolling to a element inside a scrollable DIV with pure Javascript

前端 未结 3 896
星月不相逢
星月不相逢 2020-11-29 03:56

I have a div that has overflow: scroll and I have some elements inside the DIV that are hidden. On click of a button on the page, I want to make the DIV scroll

3条回答
  •  孤独总比滥情好
    2020-11-29 04:42

    Just improved it by setting a smooth auto scrolling inside a list contained in a div

    https://codepen.io/rebosante/pen/eENYBv

    var topPos = elem.offsetTop
    
    document.getElementById('mybutton').onclick = function () {
       console.log('click')
      scrollTo(document.getElementById('container'), topPos-10, 600);   
    }
    
    function scrollTo(element, to, duration) {
        var start = element.scrollTop,
            change = to - start,
            currentTime = 0,
            increment = 20;
    
        var animateScroll = function(){        
            currentTime += increment;
            var val = Math.easeInOutQuad(currentTime, start, change, duration);
            element.scrollTop = val;
            if(currentTime < duration) {
                setTimeout(animateScroll, increment);
            }
        };
        animateScroll();
    }
    
    //t = current time
    //b = start value
    //c = change in value
    //d = duration
    Math.easeInOutQuad = function (t, b, c, d) {
        t /= d/2;
        if (t < 1) return c/2*t*t + b;
        t--;
        return -c/2 * (t*(t-2) - 1) + b;
    };
    

    I guess it may help someone :)

提交回复
热议问题