瀏覽器對(duì)象模型 (BOM) 使 JavaScript 有能力與瀏覽器"對(duì)話"。
瀏覽器對(duì)象模型 (BOM)
瀏覽器對(duì)象模型(Browser Object Model (BOM))尚無(wú)正式標(biāo)準(zhǔn)刹衫。
由于現(xiàn)代瀏覽器已經(jīng)(幾乎)實(shí)現(xiàn)了 JavaScript 交互性方面的相同方法和屬性圆恤,因此常被認(rèn)為是 BOM 的方法和屬性脂新。
Window 對(duì)象
所有瀏覽器都支持 window 對(duì)象茸苇。它表示瀏覽器窗口胁住。
所有 JavaScript 全局對(duì)象筹吐、函數(shù)以及變量均自動(dòng)成為 window 對(duì)象的成員。
全局變量是 window 對(duì)象的屬性狮崩。
全局函數(shù)是 window 對(duì)象的方法蛛勉。
甚至 HTML DOM 的 document 也是 window 對(duì)象的屬性之一:
window.document.getElementById("header");
與此相同:
document.getElementById("header");
Window 尺寸
有三種方法能夠確定瀏覽器窗口的尺寸鹿寻。
- 對(duì)于Internet Explorer、Chrome诽凌、Firefox毡熏、Opera 以及 Safari:
window.innerHeight
- 瀏覽器窗口的內(nèi)部高度(包括滾動(dòng)條)
window.innerWidth
- 瀏覽器窗口的內(nèi)部寬度(包括滾動(dòng)條) - 對(duì)于 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() - 打開(kāi)新窗口
window.close() - 關(guān)閉當(dāng)前窗口
window.moveTo() - 移動(dòng)當(dāng)前窗口
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)整當(dāng)前窗口的尺寸
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>