本文匯總 JS 宿主對象(window、screen、navigator、location、history 等)的常用屬性與方法。
(1)window 的常用屬性
//height、width 系列:
a=document.documentElement.clientHeight; //文檔可視高度,由浏覽器決定
b=document.documentElement.scrollHeight; //文檔可滾動高度,由文檔內容決定
c=document.body.clientHeight; //文檔內容 body 體高度,由文檔內容決定
d=document.documentElement.scrollTop; //文檔滾動高度,由已移動高度決定
e=window.innerHeight; //文檔可視高度,由浏覽器決定
f=window.outerHeight; //整個窗口高度(含菜單欄等),由浏覽器決定
//status 屬性可設置或返回窗口狀態欄中的文本。不少浏覽器基於安全考慮(防止釣魚攻擊)已禁止腳本化狀態欄。
window.status="helloworld 個人博客"
//defaultstatus 設置窗口狀態欄默認文本
window.defaultstatus="helloworld 個人博客"
//top、parent、self、opener:
//top 返回最頂層的先輩窗口;若窗口本身就是頂級窗口,則引用自身;若是框架,則引用包含框架的頂層窗口。
//self 相當於 window;parent 是父輩窗口;opener 讓彈出窗口可以引用打開它的窗口所定義的屬性和函數(僅頂層窗口的 opener 有效)。
function turn(){ if(window.top=window.self){ window.top.Location.href="https://www.baidu.com"; } }
//closed 檢查窗口是否已關閉:window.closed;
//name 設置或返回窗口名字:
myWindow=window.open('https://www.baidu.com','MyName','width=200,height=100');
function checkWin(){ document.write(myWindow.name) }
(2)window 的常用方法
alert():彈出提示框;confirm():顯示帶確認/取消按鈕的對話框;prompt():顯示可提示用戶輸入的對話框。
setInterval():設置定時器;clearInterval():清除定時器;setTimeout():設置超時器;clearTimeout():清除超時器。
window.open(URL,name,features,replace):打開新窗口或查找已命名窗口;window.close():關閉窗口;window.print():打印當前窗口內容。
window.moveBy(x,y):按像素移動窗口;window.moveTo(x,y):移動到 (x,y);window.scrollBy(xnum,ynum):滾動指定量;window.scrollTo(xpos,ypos):滾動到某坐標;window.resizeBy(width,height):按量縮放;window.resizeTo(width,height):縮放到某尺寸。
window.focus():把鍵盤焦點給予某窗口或對象;window.blur():把鍵盤焦點從頂層瀏覽器窗口移走。
//screen:
screen.height:屏幕高度;screen.width:屏幕寬度;screen.availheight:有效高度(除任務欄);screen.availwidth:有效寬度。
//navigator:
navigator.platform:運行浏覽器的 OS;navigator.systemLanguage:OS 默認語言;navigator.userLanguage:OS 設置語言;navigator.cpuClass:CPU 等級;navigator.appName:浏覽器名稱;navigator.appCodeName:浏覽器代碼名;navigator.appVersion:浏覽器版本;navigator.appMinorVersion:次要版本;navigator.userAgent:user-agent 頭部的值。
//location:
(1)屬性:
location.host:主機名或當前 URL 的端口號;location.hostname:主機名;location.port:端口號;location.protocol:協議;location.href:完整 URL;location.hash:# 之後的錨;location.search:查詢部分(? 及之後)。
(2)方法:
location.reload():重新加載頁面;location.assign("url"):加載新文檔;location.replace("url"):用新頁面替換當前文檔。
//history:
(1)屬性:history.length:歷史列表中的 URL 數量。
(2)方法:history.back():加載前一個 URL;history.forward():加載後一個 URL;history.go(1):正數向後、負數向前。