平時在寫界面獲取屏幕、瀏覽器寬高時,經(jīng)常會搞不清楚window、body、screen中的clientWidth、offsetWidth、width的區(qū)別,今天做一個總結(jié)幫助自己理解。
window、document、screen、body、documentElement的關(guān)系
window是瀏覽器中JavaScript的頂層對象,所有全局變量與函數(shù)都是window對象的成員,而document也是window的對象,表示當(dāng)前的瀏覽器載入的網(wǎng)頁(DOM樹)。比如像window.alert() = alert()、window.document.body.clientWidth=document.body.clientWidth。
screen也是window的對象,表示當(dāng)前瀏覽器所在的屏幕。
documentElement和body,前者是指文檔的html元素對象,后者指文檔的body對象
window相關(guān)寬高屬性
- innerWidth:瀏覽器窗口內(nèi)部寬度(包含垂直滾動條)
- innerHeight:瀏覽器窗口內(nèi)部高度(包含水平滾動條)
- outerWidth:整個瀏覽器窗口的寬度
- outerHeight:整個瀏覽器窗口的高度

window-屏幕寬高.png
document相關(guān)寬高屬性
相關(guān)的有3類屬性:
- client相關(guān)
- offset相關(guān)
- scroll相關(guān)
client相關(guān)屬性
- document.body.clientWidth:body的寬度(padding + content,不包含滾動條)
- document.body.clientHeight: body的高度
offset相關(guān)屬性
- document.body.offsetWidth:body包含border的寬度(padding + content + border)
- document.body.offsetHeight:body包含border的高度
scroll相關(guān)屬性
- document.body.scrollWidth:body可滾動的寬度,包括overflow溢出看不到的內(nèi)容
- document.body.scrollHeight:body可滾動的高度,包括overflow溢出看不到的內(nèi)容
documentElement與使用body類似,將以上body改為documentElement,測量寬高的元素就是html了。
看個例子,設(shè)置了reset.css后,設(shè)置當(dāng)前頁面的css
body {
font-family: "sans-serif";
height: 800px;
border: 40px solid orange !important;
}

client-offset-scroll.png

client-height.png
screen相關(guān)寬高屬性
- screen.width:屏幕寬度,瀏覽器最大化時的最大寬度
- screen.height:屏幕高度,瀏覽器最大化時的最大高度
- screen.availWidth:瀏覽器可使用的屏幕最大水平寬度
- screen.availHeight:瀏覽器可使用的屏幕最大的垂直高度

screen.png
如果對你有幫助的話,點(diǎn)贊、評論、贊賞都是對我的鼓勵,也是支持我寫下去的動力,筆芯~
本文原創(chuàng)發(fā)布于微信公眾號「程序員張晴天」,歡迎關(guān)注第一時間獲取最新分享,一起進(jìn)步。

程序員張晴天.png