這篇文章主要介紹了JavaScript編程中的window與window.screen對象,是JS在瀏覽器中視圖編程的基礎,需要的朋友可以參考下
Window 對象
所有瀏覽器都支持 window 對象。它表示瀏覽器窗口。
所有 JavaScript 全局對象、函數以及變量均自動成為 window 對象的成員。
全局變量是 window 對象的屬性。
全局函數是 window 對象的方法。
甚至 HTML DOM 的 document 也是 window 對象的屬性之一:
- window.document.getElementById("header");
與此相同:
- document.getElementById("header");
Window 尺寸
有三種方法能夠確定瀏覽器窗口的尺寸(瀏覽器的視口,不包括工具欄和滾動條)。
對于Internet Explorer、Chrome、Firefox、Opera 以及 Safari:
window.innerHeight - 瀏覽器窗口的內部高度
window.innerWidth - 瀏覽器窗口的內部寬度
對于 Internet Explorer 8、7、6、5:
document.documentElement.clientHeight
document.documentElement.clientWidth
或者
document.body.clientHeight
document.body.clientWidth
實用的 JavaScript 方案(涵蓋所有瀏覽器):
實例
- var w=window.innerWidth
- || document.documentElement.clientWidth
- || document.body.clientWidth;
- var h=window.innerHeight
- || document.documentElement.clientHeight
- || document.body.clientHeight;
該例顯示瀏覽器窗口的高度和寬度:(不包括工具欄/滾動條)
Window Screen
window.screen對象在編寫時可以不使用 window 這個前綴。
一些屬性:
screen.availWidth - 可用的屏幕寬度
screen.availHeight - 可用的屏幕高度
Window Screen 可用寬度
screen.availWidth 屬性返回訪問者屏幕的寬度,以像素計,減去界面特性,比如窗口任務欄。
實例
返回您的屏幕的可用寬度:
- <script>
- document.write("Available Width: " + screen.availWidth);
- </script>
以上代碼輸出為:
- Available Width: 1440
Window Screen 可用高度
screen.availHeight 屬性返回訪問者屏幕的高度,以像素計,減去界面特性,比如窗口任務欄。
實例
返回您的屏幕的可用高度:
- <script>
- document.write("Available Height: " + screen.availHeight);
- </script>
以上代碼將輸出:
- Available Height: 860
新聞熱點
疑難解答