JavaScript provides attributes for obtaining the position of HTML elements:
HTMLElement.offsetLeft
HTMLElement.offsetHeight
However, it should be noted that the values stored in these two attributes are not the relative values of the element to the entire browser. The absolute position of the canvas, but the relative position relative to the position of its parent element, that is to say, these two values are calculated based on the upper left corner of the parent element being the (0,0) point. So how to get the absolute position of an HTML element? You can use the following function:
//Get the vertical coordinate of the element
function getTop(e){
var offset=e.offsetTop;
if(e.offsetParent!=null) offset =getTop(e .offsetParent);
return offset;
}
//Get the abscissa coordinate of the element
function getLeft(e){
var offset=e.offsetLeft;
if(e. offsetParent!=null) offset =getLeft(e.offsetParent);
return offset;
}
The principle is to use the HTMLElement.offsetParent attribute, if the parent element of the current element is not empty (null), then add the current offsetTop to the original offsetTop, then continue to obtain the offsetTop of the parent element's parent element, then add it, and finally recurse the ordinate of the element relative to the entire browser canvas. The same goes for the abscissa.