偏移量(offset dimension)是javascript中的一个重要的概念。涉及到偏移量的主要是offsetLeft、offsetTop、offsetHeight、offsetWidth这四个属性。当然,还有一个偏移参照——定位父级offsetParent。本文将详细介绍该部分内容
定位父级
在理解偏移大小之前,首先要理解offsetParent。人们并没有把offsetParent翻译为偏移父级,而是翻译成定位父级,很大原因是offsetParent与定位有关
定位父级offsetParent的定义是:与当前元素最近的经过定位(position不等于static)的父级元素,主要分为下列几种情况
【1】元素自身有fixed定位,offsetParent的结果为null
当元素自身有fixed固定定位时,我们知道固定定位的元素相对于视口进行定位,此时没有定位父级,offsetParent的结果为null
[注意]firefox浏览器有兼容性问题
<div id="test" style="position:fixed"></div>
<script>
//firefox并没有考虑固定定位的问题,返回<body>,其他浏览器都返回null
console.log(test.offsetParent);
</script>
【2】元素自身无fixed定位,且父级元素都未经过定位,offsetParent的结果为<body>
<div id="test"></div>
<script>
console.log(test.offsetParent);//<body>
</script>
【3】元素自身无fixed定位,且父级元素存在经过定位的元素,offsetParent的结果为离自身元素最近的经过定位的父级元素
<div id="div0" style="position:absolute;">
<div id="div1" style="position:absolute;">
<div id='test'></div>
</div>
</div>
<script>
console.log(test.offsetParent); //<div id="div1">
</script>
【4】<body>元素的parentNode是null
console.log(document.body.offsetParent);//null