JavaScript offsetParent案例詳解
1. offsetParent定義:那么offsetParent就是距離該子元素最近的進行過定位的父元素(position:absolute relative fixed),如果其父元素中不存在定位則offsetParent為:body元 素
2. 根據(jù)定義分別存在以下幾種情況
- 元素自身有fixed定位,父元素不存在定位,則offsetParent的結果為null(firefox中為:body,其他瀏覽器返回為null)
- 元素自身無fixed定位,且父元素也不存在定位,offsetParent為<body>元素
- 元素自身無fixed定位,且父元素存在定位,offsetParent為離自身最近且經(jīng)過定位的父元素
- <body>元素的offsetParent是null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="test1" style="position:fixed"></div> <div id="test2"></div> <div id="div0" style="position:absolute;"> <div id="div1" style="position:absolute;"> <div id='test3'></div> </div> </div> <script> /* 【1】元素自身有fixed定位,父元素不存在定位,則offsetParent的結果為null(firefox中為:body,其他瀏覽器返回為null) */ var test1 = document.getElementById('test1'); console.log('test1 offsetParent: ' + test1.offsetParent); /* 【2】元素自身無fixed定位,且父元素也不存在定位,offsetParent為<body>元素 */ var test2 = document.getElementById('test2'); console.log('test2 offsetParent: ' + test2.offsetParent); /* 【3】元素自身無fixed定位,且父元素也不存在定位,offsetParent為<body>元素 */ var test3 = document.getElementById('test3'); console.log('test3 offsetParent: ' + test3.offsetParent); /* 【4】<body>元素的offsetParent是null */ */ console.log('body offsetParent: ' + document.body.offsetParent);//null </script> </body> </html>
3. IE7中對于定位的offsetParent,存在以下bug
【1】當元素本身經(jīng)過絕對定位或相對定位,且父級元素無經(jīng)過定位的元素時,IE7-瀏覽器下,offsetParent是<html>
<div id="test1" style="position:absolute;"></div> <script> //IE7-瀏覽器返回<html>,其他瀏覽器返回<body> console.log(test1.offsetParent); </script>
<div id="test2" style="position:relative;"></div> <script> //IE7-瀏覽器返回<html>,其他瀏覽器返回<body> console.log(test2.offsetParent); </script>
<div id="test3" style="position:fixed;"></div> <script> //firefox并沒有考慮固定定位的問題,返回<body>,其他瀏覽器都返回null console.log(test3.offsetParent); </script>
【2】如果父級元素存在觸發(fā)haslayout的元素或經(jīng)過定位的元素,且offsetParent的結果為離自身元素最近的經(jīng)過定位或觸發(fā)haslayout的父級元素
<div id="div0" style="display:inline-block;"> <div id='test'></div> </div> <script> //IE7-瀏覽器返回<div id="div0">,其他瀏覽器返回<body> console.log(test.offsetParent); </script>
<div id="div0" style="position:absolute;"> <div id="div1" style="display:inline-block;"> <div id='test'></div> </div> </div> <script> //IE7-瀏覽器返回<div id="div1">,其他瀏覽器返回<div id="div0"> console.log(test.offsetParent); </script>
<div id="div0" style="display:inline-block;"> <div id="div1" style="position:absolute;"> <div id='test'></div> </div> </div> <script> //所有瀏覽器都返回<div id="div1"> console.log(test.offsetParent); </script>
到此這篇關于JavaScript offsetParent案例詳解的文章就介紹到這了,更多相關JavaScript offsetParent內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript學習筆記(十九) 節(jié)點的操作實現(xiàn)代碼
javascript學習筆記之節(jié)點的操作實現(xiàn)代碼,包括節(jié)點的創(chuàng)建、添加、移除、替換、復制2012-06-06