瀏覽器對象模型 (BOM) 使 JavaScript 有能力與瀏覽器"對話"。
瀏覽器對象模型 (BOM)
瀏覽器對象模型(Browser Object Model (BOM))尚無正式標準。
由于現(xiàn)代瀏覽器已經(jīng)(幾乎)實現(xiàn)了 JavaScript 交互性方面的相同方法和屬性,因此常被認為是 BOM 的方法和屬性。
Window 對象
所有瀏覽器都支持 window 對象。它表示瀏覽器窗口。
所有 JavaScript 全局對象、函數(shù)以及變量均自動成為 window 對象的成員。
全局變量是 window 對象的屬性。
全局函數(shù)是 window 對象的方法。
甚至 HTML DOM 的 document 也是 window 對象的屬性之一:
window.document.getElementById("header");
與此相同:
document.getElementById("header");
Window 尺寸
有三種方法能夠確定瀏覽器窗口的尺寸。
- 對于Internet Explorer、Chrome、Firefox、Opera 以及 Safari:
window.innerHeight- 瀏覽器窗口的內(nèi)部高度(包括滾動條)
window.innerWidth- 瀏覽器窗口的內(nèi)部寬度(包括滾動條) - 對于 Internet Explorer 8、7、6、5:
document.documentElement.clientHeight
document.documentElement.clientWidth - 或者
document.body.clientHeight
document.body.clientWidth
例:
<p id="demo"></p>
<script>
var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h=window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
x=document.getElementById("demo");
x.innerHTML="瀏覽器window寬度: " + w + ", 高度: " + h + "。"
</script>
其他 Window 方法
一些其他方法:
window.open() - 打開新窗口
window.close() - 關閉當前窗口
window.moveTo() - 移動當前窗口
window.moveTo(x, y)
x is the horizontal coordinate to be moved to.
y is the vertical coordinate to be moved to.
例子:
<html>
<body>
<script type="text/javascript">
myWindow=window.open('','','width=200,height=100')
myWindow.document.write("This is 'myWindow'")
myWindow.moveTo(0,0)
</script>
</body>
</html>
window.resizeTo() - 調(diào)整當前窗口的尺寸
window.resizeTo(aWidth, aHeight)
aWidth is an integer representing the new outerWidth in pixels (including scroll bars, title bars, etc).
aHeight is an integer value representing the new outerHeight in pixels (including scroll bars, title bars, etc).
例子:
<html>
<body>
<button onclick="window.resizeTo(500,500)">縮小窗口</button>
</body>
</html>