Window 對(duì)象
所有瀏覽器都支持 window 對(duì)象。它表示瀏覽器窗口。
所有 JavaScript 全局對(duì)象、函數(shù)以及變量均自動(dòng)成為 window 對(duì)象的成員。
全局變量是 window 對(duì)象的屬性。
全局函數(shù)是 window 對(duì)象的方法。
甚至 HTML DOM 的 document 也是 window 對(duì)象的屬性之一:
1
|
window.document.getElementById( "header" ); |
與此相同:
1
|
document.getElementById( "header" ); |
Window 尺寸
有三種方法能夠確定瀏覽器窗口的尺寸(瀏覽器的視口,不包括工具欄和滾動(dòng)條)。
對(duì)于Internet Explorer、Chrome、Firefox、Opera 以及 Safari:
- window.innerHeight - 瀏覽器窗口的內(nèi)部高度
- window.innerWidth - 瀏覽器窗口的內(nèi)部寬度
對(duì)于 Internet Explorer 8、7、6、5:
- document.documentElement.clientHeight
- document.documentElement.clientWidth
或者
- document.body.clientHeight
- document.body.clientWidth
實(shí)用的 JavaScript 方案(涵蓋所有瀏覽器):
實(shí)例
1
2
3
4
5
6
7
|
var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var h=window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; |
該例顯示瀏覽器窗口的高度和寬度:(不包括工具欄/滾動(dòng)條)
Window Screen
window.screen對(duì)象在編寫時(shí)可以不使用 window 這個(gè)前綴。
一些屬性:
- screen.availWidth - 可用的屏幕寬度
- screen.availHeight - 可用的屏幕高度
- Window Screen 可用寬度
- screen.availWidth 屬性返回訪問者屏幕的寬度,以像素計(jì),減去界面特性,比如窗口任務(wù)欄。
實(shí)例
返回您的屏幕的可用寬度:
1
2
3
4
5
|
<script> document.write( "Available Width: " + screen.availWidth); </script> |
以上代碼輸出為:
1
|
Available Width: 1440 |
Window Screen 可用高度
screen.availHeight 屬性返回訪問者屏幕的高度,以像素計(jì),減去界面特性,比如窗口任務(wù)欄。
實(shí)例
返回您的屏幕的可用高度:
1
2
3
4
5
|
<script> document.write( "Available Height: " + screen.availHeight); </script> |
以上代碼將輸出:
1
|
Available Height: 860 |