[英]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: 它一次执行两件事:
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.
我尝试添加.scroll将其附加到我的jquery scrollTo插件上,但是没有任何反应,这可能与我使用javascript onclick无关,而href属性完全完成了其他工作。
Is there a way to attach animated smooth-scrolling to onclick="location.href='#top'" ? 有没有办法将动画平滑滚动附加到onclick =“ location.href ='#top'”?
Try this, it animates the scrollTop()
function. 试试这个,它使
scrollTop()
函数动画化。
Set link's id: 设置链接的ID:
<a id="link">link</a>
jquery to scroll: jQuery滚动:
$('#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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.