javascript smooth scroll on click

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 04:34:13

问题


I'm using this link:

<a class="" onclick="location.href='#top'" href="superContent">superContent</a>

It does two things at once:

  1. Jumps user to top of the page
  2. Performs this other (unrelated) ajax load function

Everything works great, except I'm trying to figure out how to get it to scroll to the top more smoothly. I've tried adding .scroll to attach it to my jquery scrollTo plugin, but nothing happens, which probably has something to do with the fact that I'm using javascript onclick, while the href attribute does something else entirely.

Is there a way to attach animated smooth-scrolling to onclick="location.href='#top'" ?


回答1:


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);
});



回答2:


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>


来源:https://stackoverflow.com/questions/13016379/javascript-smooth-scroll-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!