JQuery scroll()/ scrollTop()在IE或Firefox不工作 [英] JQuery scroll() / scrollTop() not working in IE or Firefox

查看:523
本文介绍了JQuery scroll()/ scrollTop()在IE或Firefox不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的脚本显示从屏幕顶部到上箭头的虚线,位置取决于用户滚动页面的距离,以便他们可以单击箭头滚动回到顶部。这在Chrome中效果很好,但在IE或Firefox中根本无法工作, 虚线不会增长,箭头也不会向下移动页面。

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');
    }
});

我试过做一个 JSFiddle 但我不认为你可以滚动,因此我不能演示这个。 / p>

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

推荐答案

Chrome使用 body 滚动,IE / Firefox滚动 html 。我个人认为 html 更有意义,但这就像我的意见,人。

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

使用<$ c $当你尝试做滚动的东西 - 包括在 $(...)。scrollTop()>'html,body' 10 。

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

请注意,我不知道需要检查未定义和调用独立位是否必要。我不知道jQuery如何对字面上通过 undefined 作为参数作出反应,所以我安全地玩。

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.

这篇关于JQuery scroll()/ scrollTop()在IE或Firefox不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆