第八章——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()