Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
916 views
in Technique[技术] by (71.8m points)

javascript - scrollTop always returns 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);
    }
});

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

document.scrollingElement.scrollTop;

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...