use*_*389 15 javascript scrolltop
我正在使用此链接:
<a class="" onclick="location.href='#top'" href="superContent">superContent</a>
Run Code Online (Sandbox Code Playgroud)
它同时做两件事:
一切都很好,除了我试图弄清楚如何让它更顺畅地滚动到顶部.我已经尝试添加.scroll将它附加到我的jquery scrollTo插件,但没有任何反应,这可能与我正在使用javascript onclick这一事实有关,而href属性完全做了其他事情.
有没有办法将动画平滑滚动附加到onclick ="location.href ='#top'"?
PRN*_*ios 40
试试这个,它动画了这个scrollTop()功能.
设置链接的ID:
<a id="link">link</a>
Run Code Online (Sandbox Code Playgroud)
要滚动的jquery:
$('#link').click(function(e){
var $target = $('html,body');
$target.animate({scrollTop: $target.height()}, 500);
});
Run Code Online (Sandbox Code Playgroud)
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;
};Run Code Online (Sandbox Code Playgroud)
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);
}Run Code Online (Sandbox Code Playgroud)
<button>click to random scroll</button>
<aside></aside>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69410 次 |
| 最近记录: |