第八章——BOM
浏覽器對象模型(Browser Object Model)
window對象
核心對象就是window,JavaScript實作上,window也是global對象。
全局作用域
在全局中定義的變量或者函數,他們都被歸為window的屬性和方法。通過window都可以通路到
var age=22
與
window.age=22
的差別
通過
var
操作符定義的變量不能通過
delete
删除,其本質是
[[Configurable]]
被設定為
false
視窗關系和架構
window.frames[]
top.frames[]
frames[]
視窗位置
實作不同,需要相容
.screenLeft
+
.screenTop
.screenX
+
.screenY
// 擷取浏覽器視窗相對螢幕的距離
function getWindowLocation() {
var left =
typeof window.screenLeft == "number"
? window.screenLeft
: window.screenX;
var top =
typeof window.screenTop == "number"
? window.screenTop
: window.screenY;
return {
left,
top,
};
}
視窗大小
實作不同,需要相容
.innerWidth
.innerHeight
.outterWidth
.outterHeight
function getWindowSize() {
var width = window.innerWidth,
height = window.innerHeight;
if (typeof width != "number") {
// 判斷相容模型
if (document.compatMode == "CSS1Compat") {
width = window.documentElement.clientWidth;
height = window.documentElement.clientHeight;
} else {
width = window.body.clientWidth;
height = window.body.clientHeight;
}
}
return {
width,
height,
};
}
設定大小
-
——直接指定大小window.resizeTo()
-
——在原有基礎上疊代window.resizeBy()
導航和打開視窗
window.open('url','架構名','視窗設定參數')
——彈出視窗,如果失敗了則傳回null
間歇調用、逾時調用
調用
setInterval()
/
setTimeout()
再過多久後将目前任務加入隊列中(并非立即執行),是以有可能間歇調用有時候順序也會錯
清除
clearInterval()
/
clearTimeout()
系統對話框
alert('注意!')
confirm('你确定嗎')
var backVal = prompt('請輸入姓名')
location對象
// location 定位對象
var url = "http://www.baidu.com/documents/mydoc.html#1";
var url = "http://www.baidu.com/documents/mydoc.html?name=gem&age=22";
console.log(location.href); // 整個url
console.log(location.host); // www.baidu.com:8080 伺服器名稱 和 端口号(如果有)
console.log(location.hostname); // www.baidu.com 伺服器名稱
console.log(location.hash); // #1 哈希
console.log(location.search); // ?name=gem&age=22 查詢值(query)
console.log(location.port); // 8080 端口号
console.log(location.pathname); // /documents/mydoc.html 檔案路徑和名
實踐
取出url中攜帶的參數并執行個體化
// 查詢字元串轉對象
function changeQueryString2Obj(str) {
var query = str.split("?")[1];
var args = {};
var items = query.length > 0 ? query.split("&") : [];
for (var i = 0; i < items.length; i++) {
var item = items[i].split("=");
if (item[0].length) {
args[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
}
}
return args;
}
console.log(
changeQueryString2Obj(
encodeURI("http://www.baidu.com/第八章.html?name=gem&age=21")
)
);
位置操作
location.assign()
——更改目前浏覽器的位置至新的URL并在記錄中添加,直接操作上述個别url屬性也會調用這個方法
location.replace()
——替代目前頁面的url,在記錄中也是
location.reload()
——重載目前頁面
navigator對象
浏覽器資訊以及用戶端資訊
navigator.plugins檢測插件
screen對象
history對象
history.go(整數)
——浏覽器頁面前進或後退
- 參數:正——向前
- 參數:負——向後
history.back()
history.forward()