Document.body.scrollTop value of 0 is a common solution to standard problems _javascript skills

Source: Internet
Author: User
When you do a page, you may use a fixed layer, 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 how did not achieve the expected effect, the output of the value of Document.body.scrollTop a look, has always been 0. It turned out to be a DTD problem, and if the page were to go straight to the beginning, there would be no problem. But to conform to the Web standards, the DTD is certainly not less. Use Document.documentElement.scrollTop instead of DOCUMENT.BODY.SCROLLTOP when you have a DTD. ­

Window.onscroll = function () {
var ofix = document.getElementById ("Divfix");
OFix.style.top = Document.documentElement.scrollTop + "px";
}

Editor's note:

When a page has a DTD (or DOCTYPE specified), use Document.documentelement.
When a page does not have a DTD (or no DOCTYPE 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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.