javascript smooth scroll on click

后端 未结 2 367
情话喂你
情话喂你 2020-12-17 14:00

I\'m using this link:

superContent

It does two thing

相关标签:
2条回答
  • 2020-12-17 14:52

    document.querySelector('button').addEventListener('click', function(){
       scrollTo( document.querySelector('aside'), Math.floor(Math.random() * 1000) + 1  , 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;
    };
    button{ float:left; }
    aside{ height:200px; width:50%; border:2px dashed red; overflow:auto; }
    aside::before{
      content:''; 
      display:block; 
      height:1000px;  
      background: linear-gradient(#3f87a6, #ebf8e1, #f69d3c);
    }
    <button>click to random scroll</button>
    <aside></aside>

    0 讨论(0)
  • 2020-12-17 14:59

    Try this, it animates the scrollTop() function.

    Set link's id:

    <a id="link">link</a>
    

    jquery to scroll:

    $('#link').click(function(e){
      var $target = $('html,body');
      $target.animate({scrollTop: $target.height()}, 500);
    });
    
    0 讨论(0)
提交回复
热议问题