窗口尺寸:
可视区的尺寸
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="100px;height:100px;border:1px solid red;padding:10px;margin:10px;"> 35 <div id="div2" style="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>