In the process of making a web page, you sometimes need to know the exact location of an element on the web page.
The following tutorial summarizes the relevant knowledge of Javascript in web page positioning.
1. The size of the web page and the size of the browser window
First of all, two basic concepts must be clarified.
The entire area of a web page is its size. Typically, the size of a web page is determined by content and CSS style sheets.
The size of the browser window refers to the area of the web page seen in the browser window, also called the viewport.
Obviously, if the content of the web page can be fully displayed in the browser window (that is, no scroll bars appear), then the size of the web page and the size of the browser window are equal. If the entire page cannot be displayed, scroll the browser window to display portions of the web page.
2. Get the size of the web page
Every element on the web page has clientHeight and clientWidth attributes. These two attributes refer to the visual area occupied by the content part of the element plus padding, excluding the space occupied by the border and scroll bar.
(Figure 1 clientHeight and clientWidth attributes)
Therefore, the clientHeight and clientWidth attributes of the document element represent the size of the web page.
function getViewport(){
if (document. compatmode == "backcompat") {
Return {
Width: Document.body.clientWidth,
Height: Document.Clientheigh
} Else { N> Return { Width: document.documentedLement.clientWidth,
Height: Document.documentedlement.clientheight
}
}
GetView above. The port function can return the browser The height and width of the window. There are three things you need to pay attention to when using it:
1) This function must be run after the page is loaded, otherwise the document object has not been generated and the browser will report an error.
2) In most cases, document.documentElement.clientWidth returns the correct value. However, in the quirks mode of IE6, document.body.clientWidth returns the correct value, so the judgment of the document mode is added to the function.
3) clientWidth and clientHeight are both read-only properties and cannot be assigned a value.
3. Another way to get the size of the web page
Each element on the web page also has scrollHeight and scrollWidth attributes, which refer to the visual area of the element including the scroll bar. .
Then, the scrollHeight and scrollWidth properties of the document object are the size of the web page, which means the entire length and width of the scroll bar.
Imitating the getViewport() function, you can write the getPagearea() function.
Copy code
Return {
Width: Document.body.scrollwidth,
Height: Document.body.ighheighheighry { Return {
width: document.documentElement.scrollWidth,
Height: document.documentElement.scrollHeight
}
}
}
However, there is a problem with this function. If the content of the web page can be fully displayed in the browser window without scroll bars, then the clientWidth and scrollWidth of the web page should be equal. But in fact, different browsers have different processing methods, and these two values are not necessarily equal. Therefore, we need to take the larger value among them, so we need to rewrite the getPagearea() function.
Copy code
The code is as follows:
function getPagearea(){
if (document.compatMode == "BackCompat"){
return {
width: Math.max(document.body.scrollWidth,
document.body.clientWidth),
height: Math.max(document.body.scrollHeight,
document.body.clientHeight)
}
} else {
return {
width: Math.max(document.documentElement.scrollWidth,
document.documentElement.clientWidth),
height: Math.max(document.documentElement.scrollHeight,
document.documentElement.clientHeight)
}
}
}
四、获取网页元素的绝对位置 网页元素的绝对位置,指该元素的左上角相对于整张网页左上角的坐标。这个绝对位置要通过计算才能得到。
首先,每个元素都有offsetTop和offsetLeft属性,表示该元素的左上角与父容器(offsetParent对象)左上角的距离。所以,只需要将这两个值进行累加,就可以得到该元素的绝对坐标。
(图二 offsetTop和offsetLeft属性)
下面两个函数可以用来获取绝对位置的横坐标和纵坐标。
function getElementLeft(element){
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null){
actualLeft = current.offsetLeft;
current = current.offsetParent;
}
return actualLeft;
}
function getElementTop(element){
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop = current.offsetTop;
current = current.offsetParent;
}
return actualTop;
}
由于在表格和iframe中,offsetParent对象未必等于父容器,所以上面的函数对于表格和iframe中的元素不适用。
五、获取网页元素的相对位置 网页元素的相对位置,指该元素左上角相对于浏览器窗口左上角的坐标。
有了绝对位置以后,获得相对位置就很容易了,只要将绝对坐标减去页面的滚动条滚动的距离就可以了。滚动条滚动的垂直距离,是document对象的scrollTop属性;滚动条滚动的水平距离是document对象的scrollLeft属性。
(图三 scrollTop和scrollLeft属性)
对上一节中的两个函数进行相应的改写:
function getElementViewLeft(element){
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null){
actualLeft = current.offsetLeft;
current = current.offsetParent;
}
if (document.compatMode == "BackCompat"){
var elementScrollLeft=document.body.scrollLeft;
} else {
var elementScrollLeft=document.documentElement.scrollLeft;
}
return actualLeft-elementScrollLeft;
}
function getElementViewTop(element){
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop = current. offsetTop;
current = current.offsetParent;
}
if (document.compatMode == "BackCompat"){
var elementScrollTop=document.body.scrollTop;
} else {
var elementScrollTop=document.documentElement.scrollTop;
}
return actualTop-elementScrollTop;
}
scrollTop 및 scrollLeft 속성에 값을 할당할 수 있으며 웹페이지를 해당 위치로 즉시 자동 스크롤하므로 웹페이지 요소의 상대적 위치를 변경하는 데 사용할 수 있습니다. 또한 element.scrollIntoView() 메서드도 유사한 효과를 가지며, 이를 통해 웹 페이지 요소가 브라우저 창의 왼쪽 상단에 표시되도록 할 수 있습니다.
6. 요소의 위치를 빠르게 가져오는 방법 위의 기능 외에도 웹페이지의 위치를 빠르게 가져오는 방법이 있습니다. 즉시 요소.
getBoundingClientRect() 메소드를 사용하는 것입니다. 이는 네 가지 속성(left, right, top, Bottom)을 포함하는 객체를 반환합니다. 이 속성은 각각 브라우저 창(뷰포트)의 왼쪽 상단 모서리를 기준으로 요소의 왼쪽 상단 모서리와 오른쪽 하단 모서리 사이의 거리에 해당합니다. .
그래서 웹페이지 요소의 상대적인 위치는
var
코드 복사
현재 IE , Firefox 3.0 및 Opera 9.5는 모두 이 방법을 지원하며 Firefox 2.x, Safari, Chrome 및 Konqueror는 지원하지 않습니다.