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

﹥>﹥吖頭↗ 提交于 2020-01-07 03:03:31

问题


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.



来源:https://stackoverflow.com/questions/35290602/jquery-scroll-scrolltop-not-working-in-ie-or-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!