简体   繁体   中英

How to scroll to the top of page in IE with jQuery

I have this Javascript below using jQuery that shows a div on a page that when clicked will slowly scroll the page back to the top of the page, it works good with chrome and firefox however when used on IE 8 it just goes to the top immediately instead of a slower scroll up

Can anyone tell me how to overcome this?

// BACK TO TOP
jQuery(window).scroll(function() {
    if (jQuery(window).scrollTop() > 0) $('#jump-link').show();
    else
    $('#jump-link').hide();
});

jQuery('#jump-link').click(function() {
    jQuery('html, body').stop().animate({
        scrollTop: 0
    }, 900);
    return false;
});

It's because of the onscroll handler being called repeatedly. Remove the onscroll handler before animating the scroll to the top, then add it back later. Id est, replace the second block with:

jQuery('#jump-link').click(function() {
    jQuery(window).unbind('scroll');
    $('#jump-link').hide();
    jQuery('html, body').stop().animate({
        scrollTop: 0
    }, 900, function() {
        jQuery(window).scroll(function() { ... });

    });
    return false;
});

Note that you can clean up the code by naming the scrolling function, and reference it by name in the unbind and re-binding functions.

(I'm assuming you've checked the even more obvious possibility of $.fx.off being true, right?)

$.fn.scrollView = function() {
return this.each(function() {
    $('html, body').animate({
        scrollTop: $(this).offset().top
    }, 1000);
});
};

and use like that

$('html').scrollView();

You can fiddle here (just scroll the bottom of page and click last list-item)

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