一、什么是BOM
- BOM(浏览器对象模型),就是对浏览器进行操作的东西
- BOM是使用window进行操作,window下面包括document,location,navigation,screen,history。
- window对象是浏览器的顶级对象
- BOM比DOM大
二、页面加载事件
如果要把js代码放在整个html页面的前面,js代码就会失效,加上onload事件就可以改变这一现状,意思就是等页面加载完成了在执行js代码
- window.onload
- window.addEventListener( ’ load’ , fn )
代码演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div{
width: 200px;
height: 200px;
background-color: aquamarine;
}
</style>
<body>
<script>
window.addEventListener('load' , function(){
var div = document.querySelector('div');
div.addEventListener( 'click' , function(){
alert('弹出来了')
})
})
</script>
<div>点击会弹出框</div>
</body>
</html>
演示结果:
不会弹出的:
会弹出的:
三、栅格布局的BOM原理(调整窗口大小)
- window.resize ---- 当屏幕发生变化重置
- window.addEventListener( ‘resize’ , fn) ---- 当屏幕发生变化重置
- window.innerWidth ---- 当前的窗口尺寸
要求:当屏幕小于800px时,隐藏div
代码演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 200px;
height: 200px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div>窗口小于800px时候隐藏</div>
<script>
window.addEventListener('load',function(){
var div = document.querySelector('div');
window.addEventListener( 'resize' , function(){
if(window.innerWidth < 800 ){
div.style.display = 'none';
} else{
div.style.display = 'block'
}
})
})
</script>
</body>
</html>
**展示结果:**自测
四、定时器
- setTimeout(回调函数,延迟毫秒)---- 只定时一次
- setInterval(回调函数,延迟毫秒)---- 循环调用
- clearTimeout () ---- 清除定时器
- clearInterval () ---- 清除定时器
五、location对象 ---- 用于设置窗体的URL
- location.href ---- 获取或者设置整个url
- location.host ---- 返回主机域名
- location.port ---- 返回端口号,没有端口号就返回字符串
- location.pathname ---- 返回路径
- location.search ---- 返回参数
- location.hash ---- 返回#后面的
- location.assign() ---- 可以跳转页面
- location.replace() ---- 替换当前页面
- location.reload() ---- 重新加载页面
- 没有就返回空的字符串
代码演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// - location.href ---- 获取或者设置整个url
console.log(location.href);
// - location.host ---- 返回主机域名
console.log(location.host);
// - location.port ---- 返回端口号,没有端口号就返回字符串
console.log(location.port);
// - location.pathname ---- 返回路径
console.log(location.pathname);
// - location.search ---- 返回参数
console.log(location.search);
// - location.hash ---- 返回#后面的
console.log(location.hash);
</script>
</body>
</html>
演示结果:
六、navigator对象 导航 ---- 用于手机端跟电脑端的切换
- navigator.userAgent
七、history
- back() ---- 页面后退功能
- forward() ---- 页面前进功能
- go() ---- 页面前进后退功能都可以,-1后退,1 前进