The difference between document.documentElement and document.body, and the height of the scroll bar in the webpage
To get the height of the scroll bar in the web page, you can get it through document.body.scrollTop, for example, make the div scroll with the scroll bar:
//html
<div id= "div" style= "width:100px;height:100px;background:#ccc;position:absolute;" >
</div>
//js
window.onscroll = function () {
var div = document.getElementById( "div" );
div.style.top = document.body.scrollTop + "px" ;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
After running, the expected effect is not achieved, and the outputdocument.body.scrollTop
The value of , is always 0. After a toss, it turned out to beDTD (Document Declaration Type)
The problem, if the page directly uses<html>
It's fine to start with. But to comply with web standards,DTD
Of course it is indispensable.
If there isDTD
when you use it, then use itdocument.documentElement.scrollTop
replacedocument.body.scrollTop
That's it.
window.onscroll = function(){
var oFix = document .getElementById ( "divfix" ) ;
oFix .style .top = document .documentElement .scrollTop + "px" ;
}
- 1
- 2
- 3
- 4
DTD related notes: The page has
DTD
, or specifyDOCTYPE
when usingdocument.documentElement
.page does not have
DTD
, or not specifiedDOCTYPE
, when usingdocument.body
.This is true in both IE and Firefox.
For compatibility, with or without DTD, the following code can be used:
var scrollTop = window .pageYOffset //for FF
|| document .documentElement .scrollTop
|| document .body .scrollTop
|| 0 ;
- 1
- 2
- 3
- 4
DocumentElement and body related instructions:
body
is the body child node in the DOM object, ie<body>
Label;documentElement
is the root node root of the entire node tree, that is<html>
Label;
DOM calls each object in the hierarchy a node, which is a hierarchical structure. You can understand it as a tree structure, just like our directory, a root directory. There are subdirectories.
Take the HTML hypertext markup language as an example: a root of the entire document is, in the DOM, you can use document.documentElement to access it, which is the root node of the entire node tree. The body is a child node. To access the body tag, you should write: document.body in the script.