BOM(Browser Object Model)提供與瀏覽器窗口交互的對象,核心是 window。雖無官方標準,但主流瀏覽器實現了事實標準。本文系統梳理 BOM 核心 API。
window 屬性/方法。window.foo 返回 undefined 不拋錯,直接 foo 會拋 ReferenceError。| 屬性 | 說明 |
|---|---|
| document | 當前文檔對象(DOM 入口) |
| location | 當前 URL 信息與導航控制 |
| history | 瀏覽歷史棧操作 |
| navigator | 瀏覽器/客戶端信息 |
| screen | 屏幕分辨率等顯示信息 |
| frames | 頁面內框架集合 |
| opener | 打開當前窗口的父窗口 |
| parent/top | 框架集合中的父/頂層窗口 |
| innerWidth/innerHeight | 視口尺寸(含滾動條) |
alert('警告信息'); // 僅提示
const confirmed = confirm('確認或取消'); // true/false
const input = prompt('請輸入', '默認值'); // 字符串/null
// 打印/查找對話框(較少用)
print(); // 彈出打印面板
find(); // 彈出查找面板
特點:同步阻塞 JS 執行,樣式由 OS/瀏覽器控制,不可 CSS 定制。
// 基礎用法
const win = window.open('https://example.com', '_blank', 'width=600,height=400,top=100,left=100');
// 參數詳解
// url: 加載地址
// target: _blank(新標籤) _self(當前) _parent _top 或窗口名
// features: 逗號分隔的特性字符串
// replace: true 替換歷史記錄,false 新增記錄
| 特性 | 值類型 | 說明 |
|---|---|---|
| width/height | 數值 | 窗口尺寸(最小 100px) |
| top/left | 數值 | 屏幕座標(非負) |
| location | yes/no | 顯示地址欄 |
| menubar | yes/no | 顯示菜單欄 |
| resizable | yes/no | 允許拖拽縮放 |
| scrollbars | yes/no | 顯示滾動條 |
| status | yes/no | 顯示狀態欄 |
| toolbar | yes/no | 顯示工具欄 |
const child = window.open('child.html');
child.onload = () => {
child.document.title = '子頁面標題'; // 操作子窗口 DOM
child.parent === window; // true
};
// 子窗口操作父窗口
window.opener.document.body.style.background = 'red';
// 窗口左上角相對屏幕座標
const left = window.screenLeft ?? window.screenX;
const top = window.screenTop ?? window.screenY;
// 移動窗口(需用戶交互觸發,否則被攔截)
window.moveTo(100, 100); // 絕對位置
window.moveBy(10, 10); // 相對偏移
// 外部尺寸(含瀏覽器邊框)
window.outerWidth / window.outerHeight
// 內部尺寸(視口,文檔可見區域)
window.innerWidth / window.innerHeight
// 調整大小
window.resizeTo(800, 600);
window.resizeBy(100, 50);
// 一次性定時器
const timerId = setTimeout(() => console.log('執行'), 1000);
clearTimeout(timerId); // 取消
// 循環定時器
const intervalId = setInterval(() => console.log('循環'), 1000);
clearInterval(intervalId); // 取消
// 傳參寫法(現代瀏覽器支持)
setTimeout((a, b) => console.log(a + b), 1000, 1, 2); // 3
location.href = 'https://example.com'; // 跳轉
location.reload(); // 刷新
location.replace(url); // 替換歷史(不可後退)
history.back(); // 後退
history.forward(); // 前進
history.go(-2); // 後退 2 步
history.pushState(state, title, url); // HTML5 歷史管理
BOM 是前端與瀏覽器窗口交互的橋樑。掌握 window 核心屬性、對話框、窗口控制、定時器、導航 API,能實現豐富的窗口級交互體驗。注意跨域限制:只能操作同源窗口的 DOM。