简体   繁体   中英

ScrollTop() function, scroll time

When function is called, the page scrolls up to the top, but I need to wait for as long as the animate time is set to, to be able to scroll down again. for example if I say

$('html, body').animate({ scrollTop: 0 }, 800);

It makes me wait for a while to be able to scroll down again, but if I write

$('html, body').animate({ scrollTop: 0 }, 10);

It scrolls up a lot faster, but I will be able to immediately scroll down again! How can I use 800 (so the animate acts cooler) but avoid waiting for scrolling down again?

$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('.goToTop').fadeIn();
    } else {
        $('.goToTop').fadeOut();
    }
    $('#goToTop').click(function () {
        $('html, body').animate({ scrollTop: 0 }, 800);
        return false;
    });
});

you can stop any ongoing animation using the following code .

$( 'html,body' ).stop();

edit: the animation has to stop only if the scroll was triggered by a human. Heres a working fiddle https://jsfiddle.net/sjp3xngo/4/

You need to write a setTimeout function inside the callback function of .animate() (the one which scrolls the window to top) in order to scroll down BACK to its earlier position. Working fiddle here .

 $(document).ready(function(){ $(window).scroll(function () { if ($(this).scrollTop() > 100) { $('#goToTop').fadeIn(); } else { $('#goToTop').fadeOut(); } }); var duration_ms = 800; $('#goToTop').click(function () { var last_scroll = $(window).scrollTop(); $('html, body').animate({ scrollTop: 0 }, duration_ms, function(){ setTimeout(function(){ $('html, body').animate({ scrollTop: last_scroll }, duration_ms); }, duration_ms); }); }); }); 
 #goToTop{ cursor: pointer; display: none; position: fixed; bottom: 15px; right: 15px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre> a b c d q w e r t y u i o p a s d f g h j k l z x c v b n m <span id="goToTop">go to top</span> </pre> 

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