文章出處
文章列表
body有默認的8px-margin;
<!doctype html> <html> <head> <meta charset="utf-8"> <title>無標題文檔</title> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"> sonsonsonsonsonsonsonsonson <div id="div4"></div> </div> </div> </div> <div id="center"></div> <style> *{ margin:0; padding:0; } body{ margin:40px; border:60px solid #0C6; padding:20px; } #div1{ border:20px solid #00e; margin:10px; background:#f00; } #div2{ position:absolute; left:10px; top:40px; border:10px solid #f00; margin:10px; padding:10px; background:#666; color:#fff; } #div3{ position:absolute; left:40px; top:40px; margin:10px; padding:10px; /*border:20px solid #fee;*/ } #div4{ margin:20px; border:100px; } #center{ position:absolute; width:100px; height:100px; background:#000; left:50%; top:50%; margin-left:-50px; margin-top:-50px; } </style> <script> //position:absoulte的offsetLeft指從有相對定位或者有絕對定位的父元素的margin-sizing開始的; //如果元素沒有定位,是根據文檔流布局,那么文檔的offsetLeft為;子元素的border-sizing到有一個定位的margin-sizing; //offsetLeft就是指從子元素的border-sizing到 一個有定位的父元素的marin-sizing,所以如果要獲取一個內層元素的offsetLeft的時候要小心,并且如果某一個絕對定位的父元素有margin,因為你獲取的 offsetLeft += offsetParent.offsetLeft, 會比實際的長; //margin會影響到 絕對定位的元素,所有就有了負邊距居中這種東西; //負邊距居中這種東西雖然影響布局有點奇怪,但是,得出的offsetLeft的確是正確的;剛剛好在中間,因為offsetLeft就是不包含margin進行計算的; //用這個 e5.getBoundingClientRect() 也好用; var e1 = document.querySelector("#div1"); var e2 = document.querySelector("#div2"); var e3 = document.querySelector("#div3"); var e4 = document.querySelector("#div4"); var e5 = document.querySelector("#center"); </script> </body> </html>
文章列表
全站熱搜