萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Window 瀏覽器物件模型 (BOM) 完整屬性與方法速查表

window 物件是瀏覽器物件模型 (BOM) 的核心,代表瀏覽器視窗實例。所有全域變數、函式皆自動成為其屬性與方法。本文系統整理 24 大類常用屬性與方法,附上語法、參數、回傳值與實務提醒,適合開發時快速查閱。

一、視窗開啟與關閉

方法語法說明回傳值
openwindow.open(url, name, specs, replace)開啟新視窗載入指定 URL。specs 為逗號分隔的特性字串(如 width=400,height=300,scrollbars=yes)新視窗的 WindowProxy 參考,若被攔截則為 null
closewindow.close()關閉當前視窗(僅限腳本開啟的視窗)undefined

常用 specs 參數速查

// 尺寸與位置
width, height, left, top, innerWidth, innerHeight, outerWidth, outerHeight, screenX, screenY

// UI 元件
toolbar, location, directories, status, menubar, scrollbars, resizable, titlebar

// 行為
fullscreen (IE), dependent (Firefox), alwaysRaised, alwaysLowered, z-lock, hotkeys

二、對話框方法

方法語法回傳值備註
alertwindow.alert(message)undefined同步阻塞,僅顯示文字
confirmwindow.confirm(message)true/false同步阻塞,確定/取消
promptwindow.prompt(message, default)string/null同步阻塞,使用者輸入
printwindow.print()undefined喚起列印對話框
findwindow.find()boolean非標準,僅部分瀏覽器支援

三、計時器

方法語法回傳值用途
setTimeoutsetTimeout(handler, delay, ...args)timerId (number)延遲一次性執行
clearTimeoutclearTimeout(timerId)undefined取消 setTimeout
setIntervalsetInterval(handler, delay, ...args)timerId (number)週期性重複執行
clearIntervalclearInterval(timerId)undefined取消 setInterval
最佳實踐:傳遞函式參考而非字串(避免 eval 風險),並在元件銷毀時統一清除計時器防止記憶體洩漏。

四、視窗幾狀控制

方法語法說明
moveBymoveBy(dx, dy)相對移動像素
moveTomoveTo(x, y)移至絕對螢幕座標
resizeByresizeBy(dw, dh)相對調整寬高
resizeToresizeTo(w, h)設定絕對寬高
現代瀏覽器常限制非使用者發起的視窗移動/縮放,建議僅在自行開啟的 popup 中使用。

五、捲軸控制

方法語法說明
scrollByscrollBy(x, y) / scrollBy(options)相對捲動,options 可含 {top, left, behavior: 'smooth'}
scrollToscrollTo(x, y) / scrollTo(options)捲動至絕對座標,支援平滑捲動
scrollscroll(x, y)scrollTo 別名

六、歷史與導航

方法/屬性說明
back()等同使用者點擊「上一頁」(需有歷史記錄)
forward()等同點擊「下一頁」
home()跳轉至首頁(非標準,極少支援)
stop()停止載入(非標準)
history.length歷史記錄筆數
history.go(delta)前進/後退指定步數

七、焦點控制

window.focus();   // 取得焦點(可能被瀏覽器阻擋)
window.blur();    // 失去焦點
// 搭配使用時需小心避免焦點閃爍迴圈

八、事件捕獲 (舊式 API,已棄用)

// 僅 IE/舊版 Netscape 支援,現代開發請使用 addEventListener
window.captureEvent(Event.CLICK | Event.MOUSEDOWN);

九、實用屬性速查

屬性說明
document當前文件的 Document 物件
locationLocation 物件,含 href, hash, search, pathname 等
historyHistory 物件
navigatorNavigator 物件,瀏覽器/裝置資訊
screenScreen 物件,螢幕解析度、色深等
localStorage / sessionStorageWeb Storage 介面
consoleConsole 除錯介面
devicePixelRatio裝置像素比
innerWidth / innerHeight視窗可視區寬高(含捲軸)
outerWidth / outerHeight瀏覽器視窗外部寬高
scrollX / scrollY文件捲動位移(別名 pageXOffset/pageYOffset)
name視窗名稱
opener開啟此視窗的父視窗參考
parent / top框架架構下的父/頂層視窗
frames框架集合
self / window指向自身

十、跨視窗通訊

// 父視窗接收訊息
window.addEventListener('message', e => {
  if (e.origin !== 'https://trusted.com') return;
  console.log('收到:', e.data);
});

// 子視窗發送訊息
window.opener.postMessage({ type: 'ready', payload: '...' }, 'https://parent.com');

結語

BOM 雖缺乏統一標準,但主流瀏覽器對核心 API 已高度趨同。掌握上表方法與屬性,即能應付 95% 的視窗操作需求。開發時請優先使用標準化的 addEventListener、postMessage、scrollTo({behavior:'smooth'}) 等現代 API,並留意 popup 被攔截、焦點搶奪、計時器洩漏等常見坑點。

copyright © 萬盛學電腦網 all rights reserved