標籤:學習筆記 body lan font function class size view bsp
視窗尺寸:
可視區的尺寸document.documentElement.clientWidthdocument.documentElement.clientHeight
滾動距離 document.documentElement.scrollTop[scrollLeft] //除了Google之外的瀏覽器解析 document.body.scrollTop[scrollLeft] //Google解析
內容寬高 obj.scrollHeight[scrollWidth]
文檔寬高 document.documentElement.offsetWidth[offsetHeight]; document.body.offsetWidth[offsetHeight];(推薦使用這個) 範例程式碼:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <title>視窗尺寸大小</title> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1"> 7 <script> 8 window.onload = function(){ 9 10 //可視區的寬度11 var width = document.documentElement.clientWidth12 console.log(‘可視區的寬度為:‘ + width + "px");13 14 //捲軸滾動距離15 document.onclick = function(){16 //相容寫法17 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;18 console.log(‘捲軸距離上面的距離為:‘ + scrollTop + "px");19 }20 21 //內容高22 var contentHeight = document.getElementById("div1").scrollHeight;23 console.log(‘內容高度為:‘ + contentHeight + "px");24 25 //文檔高26 var documentHeight1 = document.documentElement.offsetHeight; //ie10及以下會有相容性問題27 var documentHeight2 = document.body.offsetHeight; //推薦使用這種方法擷取28 29 console.log(‘文檔高度為:‘ + documentHeight2 + "px");30 }31 </script>32 </head>33 <body>34 <div id="div1" style="width:100px;height:100px;border:1px solid red;padding:10px;margin:10px;">35 <div id="div2" style="width:100px;height:200px;background-color:pink;">36 37 </div>38 </div>39 </body>40 </html>
視窗事件:
onscroll : 當捲軸滾動的時候觸發onresize : 當視窗大小發生改變的時候發生 範例程式碼:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <title>視窗事件</title> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1"> 7 <script> 8 window.onload = function(){ 9 var scrollTop = null;10 window.onscroll = function(){11 scrollTop = document.documentElement.scrollTop || document.body.scrollTop;12 console.log(‘捲軸距離上面的距離為:‘ + scrollTop + "px");13 }14 15 var windowWidth = null;16 window.onresize = function(){17 windowWidth = document.documentElement.clientWidth;18 console.log(‘可視區的寬度為:‘ + windowWidth + "px");19 }20 21 }22 </script>23 </head>24 <body style="height:2000px">25 26 </body>27 </html>
js學習筆記23----視窗尺寸及視窗事件