javascript Jquery .scroll() 不能在 IE 中同时使用 $(window) 和 $(document)。(window.pageYOffset 的问题?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18457043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:00:31  来源:igfitidea点击:

Jquery .scroll() not working in IE with both $(window) and $(document). (issue with window.pageYOffset?)

javascriptjqueryinternet-explorercross-browser

提问by MeltingDog

I have this code:

我有这个代码:

$(window).scroll(function() {
    var y_scroll_pos = window.pageYOffset;
    var scroll_pos_test = 200;   

    if(y_scroll_pos > scroll_pos_test) {

       $('.extratext').slideDown('slow');

    }
});

That works fine in FF, Chrome and IE 10 but not IE 9 or below. I have researched answers and they all say it should work with $(window)instead of the usual $(document), which is what Ive got.

这适用于 FF、Chrome 和 IE 10,但不适用于 IE 9 或更低版本。我已经研究了答案,他们都说它应该适用于$(window)而不是通常的$(document),这就是我得到的。

Does anyone know another way of amending this?

有谁知道另一种修改方法?

EDIT:

编辑:

Added console.log(y_scroll_pos);and it comes up with 'undefined'. Does IE not like window.pageYOffset;?

添加console.log(y_scroll_pos);并出现“未定义”。IE不喜欢window.pageYOffset;吗?

回答by koala_dev

From the MDN docs:

来自 MDN 文档:

For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties.

为了跨浏览器兼容性,请使用 window.pageYOffset 而不是 window.scrollY。此外,旧版本的 Internet Explorer (< 9) 不支持任一属性,必须通过检查其他非标准属性来解决。

You could always use jQuery's implementation of scrollTop(), it should work for all browsers:

你总是可以使用 jQuery 的 实现scrollTop(),它应该适用于所有浏览器:

$(window).scroll(function() {
    var y_scroll_pos = $(this).scrollTop();
    var scroll_pos_test = 200;   

    if(y_scroll_pos > scroll_pos_test) {
       $('.extratext').slideDown('slow');
    }
});