Home > Article > Web Front-end > Solution to the problem that document.body.scrollTop value is always 0. Common standard problems_javascript skills
When making pages, you may use fixed-position layers. Read document.body.scrollTop to set the position of the layer, like this:
window.onscroll = function (){
var oFix = document .getElementById("divfix");
oFix.style.top = document.body.scrollTop "px";
}
But why did it not achieve the expected effect, output document.body.scrollTop Looking at the value, it is always 0. It turns out to be a DTD problem. If the page starts directly with , there will be no problem. But to comply with web standards, DTD is of course indispensable. When you have a DTD just use document.documentElement.scrollTop instead of document.body.scrollTop.
window.onscroll = function (){
var oFix = document.getElementById("divfix");
oFix.style.top = document.documentElement.scrollTop "px";
}
Editor's Note:
When the page has a DTD (or DOCTYPE is specified), use document.documentElement.
When the page does not have a DTD (or DOCTYPE is not specified), use document.body.
This is true in both IE and Firefox.
For compatibility, you can use the following code: var scrollTop = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;