關於offsetParent

元素的offsetParent可能值:null,body元素,該元素的某個父級定位元素。javascript

 

爲null的狀況:java

  1. body元素app

  2. 元素的display爲noneblog

  3. 元素還沒有添加到DOMip

  4. 元素的position爲fixedget

爲body元素的狀況:it

  該元素不是任何一個定位元素的後代,也不是null。io

爲某個父級定位元素的狀況:table

  若是此元素是某個定位元素的子級,離它最近的父級定位元素爲此元素的offsetParent;若是此元素不是某個定位元素的子級,但其父元素中有td、th或者table,那麼其offsetParent爲上述元素。function

 

獲取元素相對於頁面的位置:

function(elem) {
	if (elem.getBoundingClientRect) { //HTML5 method
		var box = elem.getBoundingClientRect();
		var body = document.body;
		var docElem = document.documentElement;
		var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
		var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
		var clientTop = docElem.clientTop || body.clientTop || 0;
		var clientLeft = docElem.clientLeft || body.clientLeft || 0;
		var top  = box.top +  scrollTop - clientTop;
		var left = box.left + scrollLeft - clientLeft;
		return { y: Math.round(top), x: Math.round(left), width:elem.offsetWidth, height:elem.offsetHeight };
	} else { //fallback to naive approach
		var top=0, left=0;
		while(elem) {
			top = top + parseInt(elem.offsetTop,10);
			left = left + parseInt(elem.offsetLeft,10);
			elem = elem.offsetParent;
		}
		return { y: top, x: left, width:elem.offsetHeight, height:elem.offsetWidth };
	}
}
相關文章
相關標籤/搜索