1.什么是BOM
BOM(Browser Object Model)是一套操作浏览器的API(接口/方法/属性)。
BOM提供了很多对象,用于访问浏览器的功能,这些功能与任何网页内容无关。
2.常用的BOM对象
| 对象 | 描述 |
|---|---|
| window | 代表整个浏览器窗口(window是BOM中的一个对象,并且是顶级的对象) |
| navigator | 代表浏览器当前的信息,通过Navigator我们可以获取用户当前使用的是什么浏览器 |
| location | 代表浏览器当前的地址信息,通过Location我们可以获取或者设置当前的地址信息 |
| history | 代表浏览器的历史信息,通过History我们可以实现上一步/刷新/下一步操作 |
| screen | 代表用户的屏幕信息 |
其中window对象使用频率最高,我们在下节中详细讲解。
一些BOM对象常用方法
1)navigator
navigator对象表示浏览器的信息,最常用的属性包括:
例如:
<script>
console.log('appName = ' + navigator.appName);
console.log('appVersion = ' + navigator.appVersion);
console.log('language = ' + navigator.language);
console.log('platform = ' + navigator.platform);
console.log('userAgent = ' + navigator.userAgent);
</script>
2)screen
screen对象表示屏幕的信息,常用的属性有: - screen.width:屏幕宽度,以像素为单位; - screen.height:屏幕高度,以像素为单位; - screen.colorDepth:返回颜色位数,如8、16、24。
例如:
<script>
console.log("总宽度/高度: ");
console.log(screen.width + "*" + screen.height);
console.log("可以宽度/高度: ");
console.log(screen.availWidth + "*" + screen.availHeight);
console.log("颜色深度: ");
console.log(screen.colorDepth);
console.log("颜色分辨率: ");
console.log(screen.pixelDepth);
</script>
3)location
location对象表示当前页面的URL信息。 可以用location.href获取。要获得URL各个部分的值,可以这么写:
<script>
console.log(location);
console.log(location.href); //URL
console.log(location.protocol); // 协议
console.log(location.host); // 主机域名
console.log(location.port); // 端口
console.log(location.pathname); // 路径
console.log(location.search); // 参数
console.log(location.hash); // hash
</script>
4)history
history代表浏览器的历史信息.
例如:使用history实现前进和后退。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="button" value="返回" onclick="goback()">
<input type="button" value="前进" onclick="goforward()">
<a href="https://www.baidu.com/">点我</a>
<script>
function goback(){
window.history.back();
//或者
//window.history.go(-1);
}
function goforward(){
window.history.forward();
//或者
//window.history.go(1);
}
</script>
</body>
</html>