我正在使用此链接:
<a class="" onclick="location.href='#top'" href="superContent">superContent</a>
它同时做两件事:
一切都很好,除了我想弄清楚如何让它更顺畅地滚动到顶部。我已经尝试添加.scroll将它附加到我的jquery scrollTo插件,但没有任何反应,这可能与我正在使用javascript onclick这一事实有关,而href属性则完全不同。
有没有办法将动画平滑滚动添加到onclick =“location.href ='#top'”?
答案 0 :(得分:40)
试试这个,它会动画scrollTop()
函数。
设置链接的ID:
<a id="link">link</a>
要滚动的jquery:
$('#link').click(function(e){
var $target = $('html,body');
$target.animate({scrollTop: $target.height()}, 500);
});
答案 1 :(得分:4)
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>