Home  >  Article  >  Web Front-end  >  Solution to the problem that document.body.scrollTop value is always 0. Common standard problems_javascript skills

Solution to the problem that document.body.scrollTop value is always 0. Common standard problems_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:40:481104browse

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;

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn