JavaScript四大家族之offset家族

gxqsd發表於2017-08-09

javascript 元素物件擁有offset家族5大屬性(offset家族和position緊密相連)

 

offsetWidth:”元素內容的寬度”          (border+padding+width)

 

offsetHeight:”元素內容的高度”          (border+padding+height)

 

offsetLeft:”元素與瀏覽器客戶端左側的距離”    (與其父級層級最近的定位元素左側距離)

 

offsetTop:”元素與瀏覽器客戶端頂側的距離”    (與其父級層級最近的定位元素頂側距離)

 

offsetParent:”元素父級元素”          (得到其父級層級最近的定位元素物件)

 

執行下列程式碼嘗試一下

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>offset</title>
 9     <style>
10         * {
11             padding: 0;
12             margin: 0;
13         }
14 
15         .box {
16             border: 2px solid #caa;
17             padding: 1px;
18             width: 200px;
19             height: 200px;
20             background-color: yellow;
21         }
22 
23         .bigbox {
24             margin: 100px;
25             width: 200px;
26             height: 200px;
27             position: relative;
28             padding: 10px;
29             border: 1px solid red;
30         }
31 
32         .mask {
33             position: fixed;
34             right: 0;
35             bottom: 0;
36             width: 200px;
37             height: 200px;
38             background-color: red;
39         }
40     </style>
41 </head>
42 
43 <body>
44     <div id="j_mask" class="mask"></div>
45     <div id="j_bigbox" class="bigbox">
46         <div id="j_box" class="box"></div>
47     </div>
48     <button id="j_btnoffset">offset</button>
49     <button id="j_btnoffsetParent">offsetParent</button>
50 </body>
51 
52 </html>
53 <script>
54     (function () {
55         var j_btnoffset = document.getElementById("j_btnoffset"),
56             j_box = document.getElementById("j_box"),
57             j_bigbox = document.getElementById("j_bigbox"),
58             j_mask = document.getElementById("j_mask"),
59             j_btnoffsetParent = document.getElementById("j_btnoffsetParent");
60         j_btnoffset.onclick = function () {
61             var strHtml = "<p>";
62 
63             strHtml += "offsetWidth : " + j_box.offsetWidth + "";
64             strHtml += "</p>"
65             strHtml += "<p>";
66             strHtml += "offsetHeight : " + j_box.offsetHeight + "";
67             strHtml += "</p>";
68             strHtml += "<p>";
69             strHtml += "offsetLeft : " + j_box.offsetLeft + "";
70             strHtml += "</p>";
71             strHtml += "<p>";
72             strHtml += "offsetTop : " + j_box.offsetTop + "";
73             strHtml += "</p>";
74 
75             j_mask.innerHTML = strHtml;
76         };
77         j_btnoffsetParent.onclick = function () {
78             console.log(j_box.offsetParent);
79         }
80     }());
81 
82 </script>

 

 

注:當父級到body時,則以body為參照物


相關文章