要点1 BOM概念
BOM指的是浏览器对象模型,他定义了javascript的一系列接口。
主要有以下六个对象:
1.window对象
2.document对象
3.history对象
4.location对象
5.screen对象
6.navigator对象
介绍:window对象
利用window对象可以制作跑马灯效果
window.setInterval()可以设置关联延迟等功能并且回调函数
<!DOCTYPE html><html lang="en">
<head>
<meta charset="gb2312">
<title>Document</title>
</head>
<body>
<script>
var num=1;
setInterval(function()
{
num++;
console.log(num);}
,1000);
</script>
</body>
</html>
这里可以看到网页返回的是每秒打印了一个数字,如果做成按钮,就可以动态的改变了吧,具体的实现可能还需要下一个章节去实现:
同时window.clearInterval()可以清除之前的记时,效果如下
<!DOCTYPE html><html lang="en">
<head>
<meta charset="gb2312">
<title>Document</title>
</head>
<body>
<script>
var num=1;
var t=setInterval(function()
{
num++;
console.log(num);
if(num>=10)
{ window.clearInterval(t);console.log("打印结束")}
}
,1000);
</script>
</body>
</html>
settimeout的用法与clearinterval有所不同,他是只会执行一次,但是可以用递归的方法反复调用他,同样的,我们也可以用cleartimeout来清除他。
介绍2 document对象
document对象比较特殊,有属于BOM又属于DOM,是web页面内容的入口。
有以下几个方法:
document.title获取当前文档的窗口标题
document.body获取body元素对象
document.documentElement返回文档对象的根元素
document.querySelector()接受一个css选择器,是获取元素最常用的方法
例如:
document.querySelector("div")通过标签名获取
document.getElementsByClassName()通过类名获取元素集合
doucument.getElementById()通过id获取元素
document.getElementsByTagName()通过标签名获取元素集合
document.getElementsByName()通过name属性获取元素合计
histroy 对象
histroy对象有histroy.back()方法,这个方法是用来在制作网页或者app时,我们需要一个返回上一个网页,那么这里就可以用这个函数去实现这一个功能。
histroy.forward()是加载下一个Url,前提是有着一个url存在
histroy.go则是结合了两者,他把之前的功能封装成为了一个参数,1代表向后,-1代表向前找。
history.pushState()是用来保存ajax改变的变量的函数,如果接下来要用ajax改变页面,那么我们就可以利用这个函数暂存变量。
location对象
location.href()这个函数我之前也有用过,可以用这种方式来跳转到下一个网站的地址,有点像超链接的感觉。
location.reload()刷新页面。
location.assign()加载给定url的内容资源,跳转页面,这里是调用方法。
location.replace()这个方法不会保存之前的页面,也就是后退按钮会失效
screen对象
就是返回屏幕的长和宽
navigator对象
navigator.agent打印当前http请求的用户代理头的值
使用方法为console.log(navigator.userAgent);
navigator.vendor返回浏览器供应商的名称
DOM介绍
DOM是html和xml文档的编程接口。
树形结构,例子如下:
html文件
<!DOCTYPE html><html lang="en">
<head>
<meta charset="gb2312">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="mybutton.css" > <!--href中写css样式表存放的路径-->
</link>
</head>
<body>
<button class="button1" >Go</button>
<script>
var divEle=document.querySelector(".button1");
var flag=true;
divEle.onclick=function()
{
var audio = new Audio('screenshot.wav');
audio.play();
if(flag){
divEle.innerHTML="stop";
divEle.style.backgroundImage="radial-gradient(#fff 0,blue 100%)";
}
else
{
divEle.innerHTML="go";
divEle.style.backgroundImage="";
}
flag=!flag;
alert('你点击了我!')
};
</script>
</body>
</html>
CSS文件
.button1{
width: 160px;
height: 46px;
font-size: 24px;
color: white;
background-color: #fa4657;
border-radius: 23px;
cursor: pointer;
outline: none;
}
.button:hover{
opacity: .8;
}
效果