まず、各要素には、要素の左上角と親コンテナ (offsetParent オブジェクト) の左上角を示す offsetTop プロパティと offsetLeft プロパティがあります。したがって、この 2 つの値を加算するだけで、その要素の相対座標が得られます。
}
returnactualLeft-elementScrollLeft;
}
function getElementViewTop(element){
varactualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop = 現在。オフセット上;
current = current.offsetParent;
}
if (document.compatMode == "BackCompat"){
var elementScrollTop=document.body.scrollTop;
} else {
var elementScrollTop=document.documentElement.scrollTop;
}
returnactualTop-elementScrollTop;
}
The scrollTop and scrollLeft attributes can be assigned values, and will automatically scroll the web page to the corresponding position immediately, so they can be used to change the relative position of web page elements. In addition, the element.scrollIntoView() method also has a similar effect, which can make the web page element appear in the upper left corner of the browser window.
6. A quick way to get the position of an element In addition to the above functions, there is a quick way to get the position of a web page element immediately.
That is to use the getBoundingClientRect() method. It returns an object that contains four attributes: left, right, top, and bottom, which respectively correspond to the distance between the upper left corner and the lower right corner of the element relative to the upper left corner of the browser window (viewport).
So, the relative position of web page elements is
var
Copy code
Currently, IE, Firefox 3.0, and Opera 9.5 all support this method, and Firefox 2.x, Safari, Chrome, and Konqueror are not supported.