建设网站收费明细/福建seo排名
偏移量(offset dimension)是javascript中一个重要的概念。javascript中涉及到偏移的有offsetWidth、offsetHeight、offsetLeft、offsetTop这四个值,offsetLeft 和 offsetTop 都是以 offsetParent 的内边距为参照的。
console.dir(元素),可以看到下面会有offsetParent这个属性。
offsetParent 定义
HTMLElement.offsetParent 是一个只读属性,返回一个距离该元素最近的、有定位属性(position不等于static)的父级元素。如果父元素中不存在定位,则offsetParent返回body。
- 元素自身有fixed定位,offsetParent返回null;
- 元素自身无fixed定位,且父元素也不存在定位,offsetParent返回body;
- 元素自身无fixed定位,且父元素存在定位,offsetParent返回离自身最近的、有定位的父元素;
- body和document 的 offsetParent,都返回null;
offsetParent详细说明
1、元素自身有fixed定位,offsetParent返回null(firefox中为body,其他浏览器返回null)。
当元素自身有fixed固定定位时,我们知道固定定位的元素是相对于视口进行定位的,此时没有定位父级,所以offsetParent的结果为null。
<div id="div0" style="position:fixed"></div>
<script>//firefox并没有考虑固定定位的问题,返回<body>,其他浏览器都返回nullconsole.log(document.getElementById("div0").offsetParent);
</script>
2、元素自身无fixed定位,且父元素也不存在定位,offsetParent返回body。
<div><div id="div0"></div>
</div>
<script>console.log(document.getElementById("div0").offsetParent);//body
</script>
3、元素自身无fixed定位,且父元素存在定位,offsetParent返回离自身最近的、有定位的父元素。
<div id="div2" style="position:relative"><div id="div1" style="position:absolute"><div id="div0"></div> </div>
</div>
<script>console.log(document.getElementById("div0").offsetParent);//div1
</script>
4、body和document 的 offsetParent,都返回null。
console.log(document.body.offsetParent);//null
console.log(document.documentElement.offsetParent);//null
jquery中可以通过offsetParent()方法获取到元素的定位父级。
//设置最近的定位父级元素的背景颜色:
$("button").click(function(){$("p").offsetParent().css("background-color","red");
});
关于offsetWidth、offsetHeight、offsetLeft、offsetTop的详细内容可以点击查看
https://blog.csdn.net/Charissa2017/article/details/103837572
关于offsetParent的兼容补充
IE7-浏览器对于offsetParent,有以下bug。
1、当元素本身有绝对定位或者相对定位,父元素都没有定位时,IE7-浏览器中,offsetParent返回html。
<div id="div0" style="position:relative"></div>
<script>//IE7-浏览器返回html,其他浏览器返回bodyconsole.log(document.getElementById("div0").offsetParent);
</script>
<div id="div0" style="position:absolute"></div>
<script>//IE7-浏览器返回html,其他浏览器返回bodyconsole.log(document.getElementById("div0").offsetParent);
</script>
2、如果父元素有定位或者存在触发haslayout的元素,offsetParent返回离元素自身最近的有定位、或者触发haslayou的元素。
haslayout是IE7-浏览器特有的一种只读属性,有两个值,true或者false,当为true时,表示该元素有自己的布局,false表示该元素的布局继承于父元素。
点击查看haslayout的详细内容。
<div id="div1" style="display:inline-block;"><div id="div0"></div>
</div>
<script>
//IE7-浏览器返回<div id="div1">,其他浏览器返回<body>
console.log(document.getElementById("div0").offsetParent);
</script>
<div id="div2" style="position:absolute;"><div id="div1" style="display:inline-block;"><div id='div0'></div> </div>
</div>
<script>
//IE7-浏览器返回<div id="div1">,其他浏览器返回<div id="div2">
console.log(document.getElementById("div0").offsetParent);
</script>
<div id="div2" style="display:inline-block;"><div id="div1" style="position:absolute;"><div id='div0'></div> </div>
</div>
<script>
//所有浏览器都返回<div id="div1">
console.log(document.getElementById("div0").offsetParent);
</script>