offsetLeft和offsetTop属性
offsetLeft
:就是这个元素左边框外,到自己的offsetParent
对象的左边框内的距离。
offsetTop
:就是这个元素上边框外,到自己的offsetParent
对象的上边框内的距离。
offsetParent
表示自己的偏移参考盒子。
IE9,IE9+ chrome等高级浏览器下
offstParent
(表示自己的偏移参考盒子)就是自己祖先元素中,离最近的已经定位的元素。如果自己的祖先元素中,没有任何元素进行了定位,offsetParent对象就是body.
无论元素自身是否定位,该元素的offsetLeft(offsetTop)就是自身到定位的祖先元素的距离值。
IE6,IE7浏览器
IE6,7下,元素本身没有定位属性,那么自己的offsetParent对象就是自己的祖先元素中离自己最近有宽度(width)和高度(height)属性或者有定位(position)属性的父辈(祖先)元素。(
定位的元素优先级高于有宽高的父辈(祖先)元素
)
IE6,7下,元素本身有定位属性,那么元素本身的offsetParent对象就是离自己最近的有定位的父辈(祖先)元素。
IE6,7下,offsetLeft(offsetTop)就是元素本身到左(上)外边框外到offsetParent对象的左(上)边框内的距离值。
IE8
IE8的offsetParent就是离自己最近的定位属性的祖先元素。
扫描二维码关注公众号,回复: 10948367 查看本文章
IE8的offsetLeft(offsetTop)的数组,会多算一条
offsetParent
的边框值(border).
兼容方法
元素本身有定位属性,offsetParent没有边框.(所有浏览器的offsetLeft(offsetTop)的数值一致).
offsetWidth和offsetHeight(全线兼容)
元素的
offsetWidth
=width+左右padding+左右border
元素的offsetHeight
=height+上下padding+左右border
注意:如果元素没有宽度,那么所有浏览器都将把px值当做offsetWidth,而不是100%;
如果元素没有高度,用文字撑的高度,所有的浏览器都将把px值当做offsetHeight;
特别注意: IE6,7,8下,元素没有高度(文字撑开的),用currentStyle.height值是auto;
clientWidth和clientHeight(全线兼容)
clientWidth
=width+左右padding
clientHeight
=height+上下padding
注意:如果盒子没有宽度,那么所有的浏览器都将px值当做cleintWidth,而不是100%
如果盒子没有高度(用文字撑开的),IE6的clientHeight是0,其他浏览器都是数值。
补充:BOM相关复习
- 滚动条位置获取
- document.body.scrollTop || document.documentElement.scrollTop
- document.body.scrollLeft || document.documentElement.scrollLeft
- window.scrollX //高版本浏览器
- window.scrollY //高版本浏览器
- window.scrollTo(x,y) //设置滚动条
- 获取尺寸 的相应方法
- 获取可视区(浏览器窗口)尺寸
- document.documentElement.clientWidth / document.documentElement.clientHeight(不包含滚动条)
- window.innerWidth/window.innerHeight (包含滚动条)
- 获取页面的尺寸
- document.body.scrollWidth
- /document.body.scrollHeight 浏览器内容的高度
- 获取屏幕尺寸
- window.screen.width
- window.screen.height
- 元素相关的尺寸
- el.offsetWidth / el.offsetHeight 可视宽高(width/height+padding+border)
- el.offsetLeft /el.offsetTop 元素距离最近的定位父级(组先级)的距离
- el.clientWidth / el.clientHeight 元素宽高(width/height+padding)
- el.clientLeft /el.clientTop 元素的左边框和上边框的数值
- el.scrollWidth / el.scrollHeight 元素的内容宽高(如果元素内容宽/高小于元素高度时,则是元素的宽和高)
- getBoundingClientRect() 高版本浏览器
- width /height 可视宽高(width/height+padding+border)
- top bottom 元素顶/底部距离可视区顶部的距离
- left right 元素左/右距离可视区左侧的距离
- 返回值是一个对象。
- 获取可视区(浏览器窗口)尺寸
- 获取元素在页面的绝对坐标
/**
* 获取元素页面的left和top的值 高版本的写法
* @param {obj} el
*/
function getPageOffset_hv(el){
var rect=el.getBoundingClientRect();
var sX=scrollX;
var sY=scrollY;
return{
left:rect.left+sX,
top:rect.top+sY
}
}
/**
* 获取元素页面的left和top的值 兼容版本的写法
* @param {obj} el
* return []
*/
function getPageOffset_lv(el){
var l=el.offsetLeft;
var t=el.offsetTop;
while(el.offsetParent){//当前元素的父级存在
el=el.offsetParent;
//clentLeft 表示左边框 clentTop 表示上边框
l+=el.offsetLeft+el.clientLeft;
t+=el.offsetTop+el.clientTop;
}
return {
left:l,
top:t
}
}