scrollTop始终返回0 [英] scrollTop always returns 0

查看:101
本文介绍了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);
    }
});

以及在几个div内使用JQuery版本,包括body标签,再次给予我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.

推荐答案

根据实现情况,滚动文档的元素可以是< html> < body>

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

CSSOM View介绍 document.scrollingElement (参见邮件主题),返回相应的元素:

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

document.scrollingElement.scrollTop;

或者,您可以使用 window.scrollY window.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天全站免登陆