Fast Solution for Total Zero Document.body.scrollTop Value

  • 2021-06-28 08:41:58
  • OfStack

There is a function to determine whether the back top button is displayed.

The JS code is as follows:


var sTop = document.body.scrollTop;
  if(sTop>100){
    document.getElementById("sm_top").style.display="block";
  }else{
    document.getElementById("sm_top").style.display="none";
  }

However, it was found that document.body.scrollTop1 has always been 0.

Looking up the data found that it was a problem with DTD.

The page specifies DTD, that is, when DOCTYPE is specified, document.documentElement is used.

The page does not have DTD, that is, when DOCTYPE is not specified, document.body is used.

This is true for both IE and Firefox.

And my page added < !DOCTYPE html > So just the following.


 /* Determine whether the Back to Top button is displayed or not */
   window.onscroll=function(){
    var sTop = document.documentElement.scrollTop;
  if(sTop>100){
    document.getElementById("sm_top").style.display="block";
  }else{
    document.getElementById("sm_top").style.display="none";
  }
  }

The above is the solution of Document.body.scrollTop, which is always zero. I hope it will help you!


Related articles: