1. 程式人生 > >圖解clientHeight,offsetHeight,scrollHeight,scrollTop四個屬性

圖解clientHeight,offsetHeight,scrollHeight,scrollTop四個屬性

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8" />
 5         <style type="text/css">
 6             body,
 7             html {
 8                 margin: 0;
 9                 padding: 0;
10             }
11             body>div {
12                 position:absolute;
13                 top:100px;
14                 left:100px;
15                 width: 100px;
16                 height: 120px;
17                 margin: 15px;
18                 padding: 20px;
19                 border: 10px solid brown;
20                 overflow: scroll;
21             }
22             body>div>div {
23                 height: 416px;
24                 background: yellow;
25             }
26             p{
27                 margin: 0; 
28             }
29         </style>
30         <title>title</title>
31     </head>
32     <body>
33         <div>
34             <div>
35                 <p>**********</p>
36                 <p>**********</p>
37                 <p>**********</p>
38                 <p>**********</p>
39                 <p>**********</p>
40                 <p>**********</p>
41                 <p>**********</p>
42                 <p>**********</p>
43                 <p>**********</p>
44                 <p>**********</p>
45                 <p>**********</p>
46                 <p>**********</p>
47             </div>
48         </div>
49         <script>
50             var oDiv = document.getElementsByTagName("div")[0];
51             oDiv.scrollTop = oDiv.scrollHeight/2;
52             console.log(oDiv.offsetHeight); //180:height+padding+border;
53             console.log(oDiv.clientHeight); //143:padding+height-滾動條(17);
54             console.log(oDiv.scrollHeight); //456:padding+全部內容高度;
55             console.log(oDiv.scrollTop);    //228:可見內容頂部到全部內容頂部的距離;
56         </script>
57     </body>
58 </html>

複製程式碼

盒子模型圖:

其中,83和103為width和height減去滾動條寬度的值;