简体   繁体   中英

javascript smooth scroll on click

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'" ?

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

 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> 

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