window 是 BOM(Browser Object Model)所有物件的母公司。它既是所有子物件的容器,本身也提供了大量視窗控制函式。這篇文章把常用的成員依功能分類整理,當成開發時的查閱手冊。
一、全域的 window
JavaScript 裡任何全域函式或變數,本質上都是 window 的屬性:
<script type="text/javascript"> var name = "撼地神牛"; document.write(window.name); // 撼地神牛 </script>
二、window 與 self
self 與 window 完全相同,通常用來明確表示「就是目前這個視窗」:
document.write(window == self); // true,永遠相等 document.write(window.Top == window.self); // 判斷目前框架是否為主框架
window、self、window.self 三者等價。
三、window 的子物件
document、frames、history、location、navigator、screen。
四、視窗控制函式(僅 IE 支援)
moveBy():從目前位置水平移動 x 像素、垂直移動 y 像素,負值往左/往上。
moveTo():把視窗左上角移到相對於螢幕左上角的 (x, y)。
resizeBy():在目前尺寸上,寬調整 w、高調整 h,負值縮小。
resizeTo():把視窗寬高設為 w 與 h。
<body> <input type="button" value="先設置視窗固定大小!" onclick="window.resizeTo(500,500);" /> <input type="button" value="再縮小10像素!" onclick="window.resizeBy(-10,-10);" /> <input type="button" value="上!" onclick="window.moveBy(0,-5);" /> <input type="button" value="下!" onclick="window.moveBy(0, 5);" /> <input type="button" value="左!" onclick="window.moveBy(-5, 0);" /> <input type="button" value="右!" onclick="window.moveBy(5, 0);" /> <input type="button" value="移到 (100, 200)" onclick="window.moveTo(100, 200);" /> </body>
捲軸控制
scrollTo() 設為絕對位置,scrollBy() 則是在目前位置上累加。兩者容易搞混,記住「To 是終點、By 是增量」即可。
<div style="height:150%; width:150%; background-color:#ddd"> <input type="button" value="移動捲軸(絕對)" onclick="window.scrollTo(100,100);" /> <input type="button" value="移動捲軸(累加)" onclick="window.scrollBy(100,100);" /> </div>
焦點控制
focus() 讓元素取得焦點,blur() 使其失去焦點:
<div>
<input type="button" value="獲得焦點" onclick="document.getElementById('testInput').focus()" />
<input type="button" value="失去焦點" onclick="document.getElementById('testInput').blur()" />
<input type="text" value="text" id="testInput" onblur="alert('我已失去焦點')" />
</div>
開啟與關閉視窗
window.open(url, name, features, replace) 開啟新視窗並回傳該視窗的 window 物件,可用來控制它。close() 關閉視窗。opener 則實現跨視窗通訊,但必須同網域。
參數說明:url 是要載入的位址;name 是新視窗名稱(也可以是 HTML target 的值);features 是逗號分隔的特性字串;replace 說明新頁面是否取代目前的歷史紀錄。
<a href="2.html" target="2">在新視窗打開連結</a>
<a href="#" onclick="window.open('https://so.jb51.net/','2');">在已建立的視窗開新位址</a>
用普通連結先開一個名為 dreamdu 的視窗之後,再呼叫 open 時瀏覽器會先找同名視窗,有的話就在其中載入新位址。
window.open('page.html', 'newwindow',
'height=100, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')
features 常用參數:height/width(不可小於 100)、left/top(不可為負)、location(是否顯示網址列)、resizable(是否可縮放)、scrollbars(是否可捲動)、toolbar(是否顯示工具列)、status(是否顯示狀態列)。字串中每個特性以逗號分隔,特性之間不允許有空格。
兩種常見的自動彈窗時機:<body onload="openwin()"> 讀頁時彈出、<body onunload="openwin()"> 離頁時彈出。要提醒的是,現代瀏覽器多半已封鎖非使用者觸發的彈出視窗,這類寫法在實務上經常被攔下來。
對話框
alert(str) 只有一個確定鈕。confirm(str) 有確定與取消,回傳布林值,而且是排他的——使用者按下按鈕前無法進行其他操作。prompt(str1, str2) 多一個文字輸入框,第一個參數是不可修改的提示文字,第二個是輸入框的預設值。
if (confirm("確定跳大?")) {
alert("果斷跳大");
} else {
alert("猥瑣打錢");
}
var sResult = prompt("請在下面輸入你的姓名", "撼地神牛");
if (sResult != null) {
alert(sResult + "已經超越神的殺戮");
} else {
alert("無名氏已經超越神的殺戮");
}
定時器
setTimeout(fun, time) 在指定毫秒後執行一次,clearTimeout(id) 取消。setInterval(fun, time) 每隔指定時間重複執行,回傳一個 id;clearInterval(id) 依這個 id 停止。
setTimeout(function () {
document.write("3 秒後觸發");
}, 3000);
setTimeout(fun1, 5000);
function fun1() { document.write("函式名的寫法,5 秒後觸發"); }
var i = 0;
var h = setInterval(function () {
document.write("3 秒輸出一次<br/>");
i++;
if (i >= 3) {
clearInterval(h);
document.write("停止輸出");
}
}, 3000);
要注意 JavaScript 是單執行緒的,定時函式其實是「插入執行佇列」而非真正併行:
function fn() {
setTimeout(function(){ alert('can you see me?'); }, 1000);
while(true) {}
}
這個 alert 永遠不會執行,因為執行緒被無窮迴圈佔住了。
location:解析 URL
屬性有 href、protocol、host、hostname、port、pathname、search、hash:
document.write(location.href + "<br/>"); // https://localhost:4889/javascriptTest.html document.write(location.protocol + "<br/>"); // http: document.write(location.host + "<br/>"); // localhost:4889 document.write(location.hostname + "<br/>"); // localhost document.write(location.port + "<br/>"); // 4889 document.write(location.pathname + "<br/>"); // /javascriptTest.html document.write(location.search + "<br/>"); // ?id=1&name=張三 document.write(location.hash); // #kk=你好?id=1&name=張三
載入新文件的四種方式:
location.reload(); // 重新載入 location.replace(); // 本視窗載入新文件,不留歷史紀錄 location.assign(); // 本視窗載入新文件,保留歷史紀錄 location = "https://so.jb51.net/"; // 跳轉到指定網址 location = "search.html"; // 相對路徑跳轉 location = "#top"; // 跳到頁面頂部
瀏覽器與螢幕資訊
navigator.appName(瀏覽器全稱)、appVersion(廠商與版本細節)、userAgent(絕大部分客戶端資訊)、platform(作業系統)。
document.write(navigator.userAgent + "<br/>"); // Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 document.write(navigator.appName + "<br/>"); // Netscape document.write(navigator.appVersion + "<br/>"); document.write(navigator.platform); // Win32
歷史紀錄則是 history.back()、forward()、go(-2)(後退兩筆),行為與瀏覽器的前後頁按鈕相同。
視窗關係
parent == self 只有頂層視窗才成立。parent 與 top 允許腳本參照視窗的祖先,通常用來取得最外層視窗。
event 事件物件
最實用的兩個操作是阻止冒泡與取消預設行為。有些時候 return false 不管用,改用下面這組就會有效:
// IE window.event.cancelBubble = true; // 停止冒泡 window.event.returnValue = false; // 阻止預設行為 // 標準瀏覽器 event.preventDefault(); // 取消預設行為 event.stopPropagation(); // 阻止事件傳遞
補充:標準環境的差異
上面標註「僅 IE 有效」的視窗控制函式(moveBy、moveTo、resizeBy、resizeTo)在現代瀏覽器中基於安全性考量已被移除或限制,只對 window.open 開啟的視窗有部分效果。同樣地,document.all、attachEvent 這類 IE 專屬 API 也不該出現在新專案裡——事件綁定請統一用 addEventListener,並把判斷式寫成「標準優先、IE 降級」的順序。
以上就是 window 物件各類成員的完整整理,涵蓋全域特性、視窗控制、定時器、location 解析、瀏覽器資訊與事件處理。