简体   繁体   中英

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. 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/

The default action upon clicking a link with a href of # is to bring the user to the top of the page. Since you did not call preventDefault on that event, the browser goes ahead and does it. 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.

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/

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.

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