scrollTop 总是返回 0 [英] scrollTop always returns 0

查看:37
本文介绍了scrollTop 总是返回 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过使用 scrollTop 和 scrollTop() 并且它总是返回 0.怎么会这样,我已经试过这样了:

I've tried using scrollTop as well as scrollTop() and it always returns 0. How can this be, I've tried it like this:

Template.myHome.events({
    "click .examine": function(event){
        event.preventDefault();

        varPos = event.clientY;
        var yPos = document.body.scrollTop;
        console.log("Y coords: " + yPos);
    }
});

以及在包含 body 标记的多个 div 上使用 JQuery 版本,再次全部给我 0 或 null.

as well as using the JQuery version on several div's within and including the body tag, again all giving me 0 or null.

我只想得到当用户向下滚动页面时在 y 轴上遍历的像素数.

All I simply want is to get the number of pixels traversed on the y-axis as the user scroll downs the page.

推荐答案

根据实现的不同,滚动文档的元素可以是 .

Depending on the implementation, the element that scrolls the document can be <html> or <body>.

CSSOM 视图引入了 document.scrollingElement(参见邮件主题),返回适当的元素:

CSSOM View introduces document.scrollingElement (see mailing thread), which returns the appropriate element:

document.scrollingElement.scrollTop;

或者,您可以使用 window.scrollYwindow.pageYOffset.它们是别名并返回相同的值,但后者具有更多浏览器支持.

Alternatively, you can use window.scrollY or window.pageYOffset. They are aliases and return the same value, but the latter has more browser support.

对于不支持上述任何一项的浏览器,您可以检查这两项:

For browsers which don't support any of the above, you can check both of these:

document.documentElement.scrollTop;
document.body.scrollTop;

var scrollTests = document.getElementById('scrollTests');
var tests = [
  "document.body.scrollTop",
  "document.documentElement.scrollTop",
  "document.scrollingElement.scrollTop",
  "window.scrollY",
  "window.pageYOffset"
];
for(var i=0; i<tests.length; ++i) {
  var p = scrollTests.appendChild(document.createElement('p'));
  p.appendChild(document.createTextNode(tests[i] + ' = '));
  p.appendChild(document.createElement('span')).id = tests[i];
}
window.onscroll = function() {
  for(var i=0; i<tests.length; ++i) {
    try{ var val = eval(tests[i]); }
    catch(err) { val = '[Error]'; }
    document.getElementById(tests[i]).innerHTML = val;
  }
};

#scrollTests {
  position: fixed;
  top: 0;
}
body:after {
  content: '';
  display: block;
  height: 999999px;
}

<div id="scrollTests"></div>

这篇关于scrollTop 总是返回 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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