简体   繁体   English

平滑滚动不起作用

[英]Smooth scrolling does not work

I want to do that when you click on the link scroll smoothly moves up. 我想这样做,当您单击链接时,滚动会平滑地向上移动。 But somehow setTimeout does not work. 但是以某种方式setTimeout不起作用。 Here's the code: 这是代码:

window.onscroll = function(e) {
    var a = document.getElementsByTagName('a')[0];
    a.style.opacity = (window.pageYOffset > document.documentElement.clientHeight) ? 1 : 0;
}

document.getElementsByTagName('a')[0].onclick = top;

function top() {
    if(window.pageYOffset != 0){
        window.scrollBy(0, -10);
        setTimeout(top, 100);
    }
}

Link to the sandbox: http://jsfiddle.net/b7by1so8/ 链接到沙箱: http : //jsfiddle.net/b7by1so8/

The default action upon clicking a link with a href of # is to bring the user to the top of the page. 单击具有href值为#的链接时的默认操作是将用户带到页面顶部。 Since you did not call preventDefault on that event, the browser goes ahead and does it. 由于您没有在该事件上调用preventDefault ,因此浏览器将继续执行该操作。 You probably want to prevent it so you can do it yourself: 您可能想阻止它,以便自己进行:

function top(e) {
    if(e) e.preventDefault();
    // ...
}

As icktoofay answered, you have to use preventDefault to cancel the default behaviour of the link. 正如icktoofay回答的那样,您必须使用preventDefault来取消链接的默认行为。

To go further, you might also want to stop the animation if the user has scrolled. 更进一步,如果用户已滚动,则可能还需要停止动画。 To do so, you can save the position of the scroll every time you change it and if the next time it doesn't match, then you have to stop the animation. 为此,您可以在每次更改时保存滚动的位置,如果下次不匹配,则必须停止动画。

Here is an example: http://jsfiddle.net/BaliBalo/b7by1so8/1/ 这是一个示例: http : //jsfiddle.net/BaliBalo/b7by1so8/1/

As said in this fiddle you can also use a decelarating speed to make things less linear by multiplicating scrollTop by a "slightly-less-to-1" number instead of just decrementing it. 就像在这个小提琴中所说的那样,您还可以使用降级速度,通过将scrollTop乘以“略小于1”的数字而不是递减来使线性度降低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM