取得瀏覽器視窗相對於螢幕左上角的座標,需兼顧兩套命名:
var leftPos = (typeof window.screenLeft == "number") ? window.screenLeft : window.screenX; var topPos = (typeof window.screenTop == "number") ? window.screenTop : window.screenY;
取得頁面視口(viewport)的尺寸:
var pageWidth = window.innerWidth,
pageHeight = window.innerHeight;
if (typeof pageWidth != "number") {
if (document.compatMode == "CSS1Compat") {
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
} else {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
}
window.open() 共有四個參數,實務上通常只需要第一個(URL)與第二個(目標)。目標可以是 _self、_parent、_top、_blank,或某個框架的名稱。
window.open("https://www.baidu.com");
window.open("https://www.baidu.com", "_blank");
window.open("https://www.baidu.com", "topFrame",
"height=400,width=400,top=10,left=10,resizable=yes");
topFrame.resizeTo(500, 300); // 調整視窗大小
topFrame.moveTo(100, 100); // 移動視窗位置
topFrame.close(); // 關閉新開的視窗
補充:出於安全考量,現代瀏覽器只允許腳本關閉「由腳本自己開啟」的視窗;對使用者手動開啟的分頁呼叫 close() 通常無效。
location.href = "https://www.baidu.com"; // 載入新網址
location.assign("https://www.baidu.com"); // 同上
window.location = "https://www.baidu.com"; // 同上
location.replace("https://www.baidu.com"); // 同上,但不留下歷史紀錄,無法回退
location.reload(); // 重新載入,可能來自快取
location.reload(true); // 強制向伺服器重新擷取
location.search; // 回傳網址中的查詢字串,以 ? 開頭
function getQueryStringArgs() {
var qs = (location.search.length > 0) ? location.search.substring(1) : "";
var args = {};
var items = qs.split("&");
for (var i = 0; i < items.length; i++) {
var item = items[i].split("=");
var name = decodeURIComponent(item[0]);
var value = decodeURIComponent(item[1]);
args[name] = value;
}
return args;
}
// 假設網址為 ?q=javascript&num=10
var args = getQueryStringArgs();
alert(args["q"]); // "javascript"
alert(args["num"]); // "10"
現在更簡便的方式是直接用 URLSearchParams;但理解上面這段手動解析的邏輯,仍有助於掌握編碼與解碼的環節。
history.go(-1); // 後退一頁
history.go(1); // 前進一頁
history.go(2); // 前進兩頁
history.go("baidu.com"); // 跳到最近的 baidu.com 頁面
history.back(); // 後退一頁
history.forward(); // 前進一頁
判斷當前頁是否為使用者開啟的第一個頁面:
if (history.length == 0) {
// 若是第一個頁面,執行某些操作
}
window.onload 會在頁面(含圖片等資源)載入完畢後觸發,很適合放初始化邏輯:
window.onload = function () {
// 執行某些操作
};
要注意 onload 是「全部資源都載完」才觸發,若圖片很大可能等很久。若你只想在 DOM 就緒時執行,可以改用 DOMContentLoaded 事件,會更早、也更符合多數互動初始化的需求。