1. 程式人生 > >js學習筆記23----窗口尺寸及窗口事件

js學習筆記23----窗口尺寸及窗口事件

推薦 距離 bsp spa cnblogs offset borde code ini

窗口尺寸:

可視區的尺寸 document.documentElement.clientWidth document.documentElement.clientHeight
滾動距離 document.documentElement.scrollTop[scrollLeft] //除了谷歌之外的瀏覽器解析 document.body.scrollTop[scrollLeft] //谷歌解析
內容寬高 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.clientWidth 12 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----窗口尺寸及窗口事件