1.offsetWidth和offsetHeight
offsetWidth和offsetHeight适用于检测元素自身的宽和高,其中:
offsetWidth=width+border+padding;(不包括元素自身的margin值)
offsetHeight=height+border+padding;(不包括元素自身的margin值)
注意:div.offsetWidth和div,offsetHeight的返回值为number类型,没有单位。
2.offsetTop和offsetLeft
offsetTop和offsetLeft适用于返回该元素相对于他的父盒子的距离,
(1)若该元素有明确定位的父盒子,则offsetLeft返回距离父盒子左边的距离,offsetTop返回距离父盒子上边的距离;
offsetLeft和offsetTop从父盒子的padding开始算起,不包括父盒子的border;
如果给定盒子的位置信息,如:
此时offsetTop和offsetLeft的值和父盒子的padding值无关,offsetTop=50,offsetLeft=30.
(2)若该元素没有明确定位的父盒子,则以body为参照,而此时:
offsetLeft + "px"=style.left
offsetLeft和style.left的区别:
a.style.left只能以行内式的形式进行定义,返回值为带有”px“的字符串,否则返回空字符串;
b.offsetLeft可以返回没有明确定义父盒子时,元素距离body的距离,返回值为number型;
c.style.left可读写,可以获取值,也可以定义值;而offsetLeft只能获取值
3.offsetParent
offsetParent适用于返回该元素的父盒子,
(1)若该元素的父盒子有定位(position=absolute/fixed/relative),则直接返回父盒子;
如该元素的父盒子没有定位,则返回body。
(2)若该盒子之上的每一级盒子都有定位,则返回距离最近的父盒子。