JQuery scroll() / scrollTop() not working in IE or

2019-08-29 05:15发布

问题:

The script below displays a dotted line from the top of the screen to an up arrow which position depends on how far down the page the user has scrolled so that they can then click the arrow to scroll back to the top. This works great in Chrome but doesn't work at all in IE or Firefox, i.e. the dotted line does not grow nor does the arrow move down the page on scroll.

Does anyone know why this is?

HTML:

<div id="dotted-line">
    <div id="up-arrow">^up</div>
</div>

JS:

$(window).scroll(function(){
    if ($(window).scrollTop() > 10) {
        var pos = $('body').scrollTop();
        $('#dotted-line').css('height',pos/4);
        $('#up-arrow').css('top',pos/4);
    } else {
        $('#dotted-line').css('height','6px');
        $('#up-arrow').css('top','-150px');
    }
});

P.S. I've tried doing a JSFiddle but I don't think you can scroll, therefore I cannot demonstrate this.

回答1:

Chrome scrolls with body, IE/Firefox scroll with html. Personally I think html makes more sense, but that's just like my opinion, man.

Use 'html,body' as a selector when attempting to do stuff with scroll - that includes in your $(...).scrollTop() > 10 check.

To avoid re-evaluating the selector every time, consider wrapping the code:

(function(undefined) {
    var container = $("html,body");
    $.windowScrollTop = function(newval) {
        if( newval === undefined) {
            return container.scrollTop();
        }
        else {
            return container.scrollTop(newval);
        }
    }
})();
// call $.windowScrollTop() to get position
// call $.windowScrollTop(100) to set position to 100

Note that I'm not sure how necessary the "check for undefined and call separately" bit is needed. I'm not sure how jQuery would react to being literally passed undefined as an argument, so I'm playing it safe.