【JavaScript】50_终篇_编程进阶与BOM编程概览(3k字+)
文章目录
- 使用 cloneNode() 方法对节点进行复制时,它会复制节点的所有特点包括各种属性 这个方法默认只会复制当前节点,而不会复制节点的子节点 可以传递一个true作为参数,这样该方法也会将元素的子节点一起复制 在本案例中,像li是一个节点,里面的“孙悟空”是一个子节点,需要使用true来一块复制上 <body> <button id="btn01">点我一下</button> <ul id="list1"> <li id="l1">孙悟空</li> <li id="l2">猪八戒</li> <li id="l3">沙和尚</li> </ul> <ul id="list2"> <li>蜘蛛精</li> </ul> <script> //点击按钮后,将id为l1 的元素添加到list2中 const list2 = document.getElementById('list2') const l1 = document.getElementById('l1') const btn01 = document.getElementById("btn01") btn01.onclick = function(){ const new1 = l1.cloneNode(true)//用来对节点进行复制 new1.id = 'new1'; list2.appendChild(new1)//将一元素添加到父节点的末尾 } </script> </body>
- 修改样式的方式:元素.style.样式名 = 样式值 如果样式名中含有-,则需要将样式表修改为驼峰命名法 <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> .box1 { width: 200px; height: 200px; background-color: #bfa; } </style> </head> <body> <button id="btn">点我一下</button> <hr> <div class="box1"></div> <script> //点击按钮后,修改box1的宽度 const btn = document.getElementById('btn') const box1 = document.querySelector('.box1') btn.onclick = function(){ //修改box1的样式 //修改样式的方式:元素.style.样式名 = 样式值 //如果样式名中含有-,则需要将样式表修改为驼峰命名法 //background-color ---> backgroundColor box1.style.width = '400px' box1.style.height = '400px' box1.style.backgroundColor = 'yellow' } </script> </body>
-
- 元素.clientWidth 获取元素内部的宽度和高度(包括内容区和内边距)
- 元素.offsetWidth
获取元素的可见框的大小(包括内容区、内边距和边框)
- 元素.scrollWidth - 获取元素滚动区域的大小
- 获取元素的定位父元素 定位父元素:离当前元素最近的开启了定位的祖先元素, 如果所有的元素都没有开启定位则返回body
- 元素.offsetLeft - 获取元素相对于其定位父元素的偏移量
- 元素.scrollLeft - 获取或设置元素滚动条的偏移量 <style> #box1 { width: 200px; height: 200px; padding: 50px; margin: 50px; border: 10px red solid; background-color: #bfa; overflow: auto; } #box2 { width: 100px; height: 500px; background-color: orange; } </style> </head> <body> <button id="btn">点我一下</button> <hr> <div> <div id="box1"> <div id="box2"></div> </div> </div> <script> const btn = document.getElementById('btn') const box1 = document.getElementById('box1') btn.onclick = function(){ console.log(box1.scrollHeight) console.log(box1.scrollWidth) console.log(box1.offsetParent) console.log(box1.offsetLeft) console.log(box1.offsetTop) console.log(box1.scrollTop) } </script> </body>
- 除了直接修改样式外,也可以通过修改class属性来间接的修改样式
- 可以一次性修改多个样式 对JS和CSS进行解耦
- 是一个对象,对象中提供了对当前元素的类的各种操作方法 元素.classList.add() :向元素中添加一个或多个class 元素.classList.remove(): 移除元素中的一个或多个class 元素.classList.toggle() :切换元素中的class 元素.classList.replace(): 替换class 元素.classList.contains() :检查class <style> .box1 { width: 200px; height: 200px; background-color: #bfa; } .box2{ background-color: yellow; width: 300px; height: 500px; border: 10px greenyellow solid; } </style> </head> <body> <button id="btn">点我一下</button> <hr> <div class="box1 box3 box4"></div> <script> //点击按钮后,修改box1的宽度 const btn = document.getElementById("btn") const box1 = document.querySelector(".box1") btn.onclick = function(){ //除了直接修改样式外,也可以通过修改class属性来间接的修改样式 // box1.className += 'box2' // box1.classList.add('box2','box3','box4') // box1.classList.add('box1') // box1.classList.remove('box2') box1.classList.toggle('box2') // box1.classList.replace('box2') let result = box1.classList.contains('box3') console.log(result) } </script> </body>
- 在DOM中存在着多种不同类型的事件对象
- event.target 触发事件的对象 event.currentTarget 绑定事件的对象(同this) event.stopPropagation() 停止事件的传导 event.preventDefault() 取消默认行为
- 事件的冒泡就是指事件的向上传到 当元素上的某个事件被触发后,其祖先元素上的相同事件也会同时被触发 冒泡的存在大大的简化了代码的编写,但是在一些场景下我们并不希望冒泡存在 不希望事件冒泡时,可以通过事件对象来取消冒泡 在事件的响应函数中:
- 表示的是触发事件的对象 this 绑定事件的对象
- 取消事件的传导 <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> #box1 { width: 300px; height: 300px; background-color: greenyellow; } #box2 { width: 250px; height: 250px; background-color: #ff0; } #box3 { width: 200px; height: 200px; background-color: orange; } </style> </head> <body> <div id="box1"> <div id="box2"> <div id="box3"></div> </div> </div> <a id="chao" href="https://lilichao.com">超链接</a> <script> const box1 = document.getElementById("box1") const box2 = document.getElementById("box2") const box3 = document.getElementById("box3") const chao = document.getElementById("chao") chao.addEventListener('click',(event) =>{ event.preventDefault(); alert('被点了一下') }) box1.addEventListener('click',function (event){ alert(event) console.log(event.target)//event.target 表示的是触发事件的对象 console.log(this)//this 绑定事件的对象 console.log(event.currentTarget) alert("hello 我是box1") }) box2.addEventListener('click',function(event){ event.stopPropagation() alert('我是box2') }) box3.addEventListener('click',function(event){ event.stopPropagation()//取消事件的传导 alert('我是box3') }) </script> </body>
- BOM 浏览器对象模型 BOM为我们提供了一组对象,通过这组对象可以完成对浏览器的各种操作 BOM对象: Window —— 代表浏览器窗口(全局对象) Navigator —— 浏览器的对象(可以用来识别浏览器) Location —— 浏览器的地址栏信息 History —— 浏览器的历史记录(控制浏览器前进后退) Screen —— 屏幕的信息 BOM对象都是作为window对象的属性保存的,所以可以直接在JS中访问这些对象 <script> console.log(history) </script>
- Navigator —— 浏览器的对象(可以用来识别浏览器)
- location 表示的是浏览器地址栏的信息 可以直接将location的值修改为一个新的地址,这样会使得网页发生跳转 location.assign() 跳转到一个新的地址 location.replace() 跳转到一个新的地址(无法通过回退按钮回退) location.reload() 刷新页面,可以传递一个true来强制清缓存刷新 location.href 获取当前地址 <body> <button id="btn">点我一下</button> <input type="text" name="username" id=""> <script> const btn = document.getElementById("btn") btn.addEventListener('click',() => { console.log(location.href)//当前地址 // location = 'https://www.lilichao.com'//使得点击按钮后,发生跳转,实现标签a的功能,通过JavaScript // location.assign('https://www.lilichao.com') location.replace('https://www.lilichao.com') }) </script> </body>
- 通过定时器,可以使代码在指定时间后执行
设置定时器的方式有两种:
- 参数: 回调函数(要执行的代码) 间隔的时间(毫秒) 关闭定时器
- 每间隔一段时间代码就会执行一次 参数: 回调函数(要执行的代码) 间隔的时间(毫秒) 关闭定时器
- <body> <h1 id="num"></h1> <script> // const timer = setTimeout(()=>{ // alert('我是定时器中的代码') // },3000)//只执行一次 // clearTimeout(timer) const numH1 = document.getElementById('num') let num = 0 const timer = setInterval(() => { num++ numH1.textContent = num if(num === 200){ clearInterval(timer) } },3000) </script> </body>
-
- 函数在每次执行时,都会产生一个执行环境 执行环境负责存储函数执行时产生的一切数据 问题:函数的执行环境要存储到哪里呢? 函数的执行环境存储到了一个叫做调用栈的地方 栈,是一种数据结构,特点 后进先出 队列,是一种数据结构,特点 先进先出
- - 调用栈负责存储函数的执行环境 - 当一个函数被调用时,它的执行环境会作为一个栈帧 插入到调用栈的栈顶,函数执行完毕其栈帧会自动从栈中弹出 ```html <script> function fn(){ let a = 10 let b = 20 function fn2(){ console.log('fn2') } fn2() console.log('fn~') } fn() console.log(1111) </script> ``` 队列,是一种数据结构,特点 先进先出
- 消息队列负责存储将要执行的函数 当我们触发一个事件时,其响应函数并不是直接就添加到调用栈中的。 因为调用栈中有可能会存在一些还没有执行完的代码 事件触发后,JS引擎是将事件响应函数插入到消息队列中排队 <body> <button id="btn">点我一下</button> <button id="btn02">点我一下2</button> <script> function fn(){ let a = 10 let b = 20 function fn2(){ console.log('fn2') } fn2() console.log('fn~') } fn() console.log(1111) const btn = document.getElementById("btn") const btn02 = document.getElementById("btn02") btn.onclick = function(){ alert(1111) const begin = Date.now() while(Date.now() - begin < 3000){ } } btn02.onclick = function () { alert(2222) } </script> </body>
使用 cloneNode() 方法对节点进行复制时,它会复制节点的所有特点包括各种属性
这个方法默认只会复制当前节点,而不会复制节点的子节点
可以传递一个true作为参数,这样该方法也会将元素的子节点一起复制
在本案例中,像li是一个节点,里面的“孙悟空”是一个子节点,需要使用true来一块复制上
<body>
<button id="btn01">点我一下</button>
<ul id="list1">
<li id="l1">孙悟空</li>
<li id="l2">猪八戒</li>
<li id="l3">沙和尚</li>
</ul>
<ul id="list2">
<li>蜘蛛精</li>
</ul>
<script>
//点击按钮后,将id为l1 的元素添加到list2中
const list2 = document.getElementById('list2')
const l1 = document.getElementById('l1')
const btn01 = document.getElementById("btn01")
btn01.onclick = function(){
const new1 = l1.cloneNode(true)//用来对节点进行复制
new1.id = 'new1';
list2.appendChild(new1)//将一元素添加到父节点的末尾
}
</script>
</body>
修改样式的方式:元素.style.样式名 = 样式值
如果样式名中含有-,则需要将样式表修改为驼峰命名法
<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>
.box1 {
width: 200px;
height: 200px;
background-color: #bfa;
}
</style>
</head>
<body>
<button id="btn">点我一下</button>
<hr>
<div class="box1"></div>
<script>
//点击按钮后,修改box1的宽度
const btn = document.getElementById('btn')
const box1 = document.querySelector('.box1')
btn.onclick = function(){
//修改box1的样式
//修改样式的方式:元素.style.样式名 = 样式值
//如果样式名中含有-,则需要将样式表修改为驼峰命名法
//background-color ---> backgroundColor
box1.style.width = '400px'
box1.style.height = '400px'
box1.style.backgroundColor = 'yellow'
}
</script>
</body>
- 它会返回一个对象,这个对象中包含了当前元素所有的生效的样式
- 参数:
- 要获取样式的对象
- 要获取的伪元素
- 返回值: 返回的一个对象,对象中存储了当前元素的样式
- 注意: 样式对象中返回的样式值,不一定能来拿来直接计算 所以使用时,一定要确保值是可以计算的才去计算
<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>
.box1 {
width: 200px;
background-color: #bfa;
}
.box1::before {
content: 'hello';
color:red
}
</style>
</head>
<body>
<button id="btn">点我一下</button>
<hr>
<div class="box1"></div>
<script>
const btn = document.getElementById("btn")
const box1 = document.querySelector(".box1")
btn.onclick = function(){
const styleObj = getComputedStyle(box1)
console.log(styleObj.width)
console.log(styleObj.left)
console.log(parseInt(styleObj.width) + 100 + 'px')
console.log(styleObj.backgroundColor)
const beforeStyle = getComputedStyle(box1,'::before')
console.log(beforeStyle.color)//返回的是rgb数值
console.log(box1.firstElementChild)
}
</script>
</body>
<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>
.box1 {
width: 200px;
background-color: #bfa;
}
.box1::before {
content: 'hello';
color:red
}
</style>
</head>
<body>
<button id="btn">点我一下</button>
<hr>
<div class="box1"></div>
<script>
const btn = document.getElementById("btn")
const box1 = document.querySelector(".box1")
btn.onclick = function(){
const styleObj = getComputedStyle(box1)
console.log(styleObj.width)
console.log(styleObj.left)
console.log(parseInt(styleObj.width) + 100 + 'px')
console.log(styleObj.backgroundColor)
const beforeStyle = getComputedStyle(box1,'::before')
console.log(beforeStyle.color)//返回的是rgb数值
console.log(box1.firstElementChild)
}
</script>
</body>

元素.clientWidth
- 获取元素内部的宽度和高度(包括内容区和内边距)
元素.offsetWidth
- 获取元素的可见框的大小(包括内容区、内边距和边框)
元素.scrollWidth
- 获取元素滚动区域的大小
- 获取元素的定位父元素
- 定位父元素:离当前元素最近的开启了定位的祖先元素, 如果所有的元素都没有开启定位则返回body
元素.offsetLeft
- 获取元素相对于其定位父元素的偏移量
元素.scrollLeft
- 获取或设置元素滚动条的偏移量
<style>
#box1 {
width: 200px;
height: 200px;
padding: 50px;
margin: 50px;
border: 10px red solid;
background-color: #bfa;
overflow: auto;
}
#box2 {
width: 100px;
height: 500px;
background-color: orange;
}
</style>
</head>
<body>
<button id="btn">点我一下</button>
<hr>
<div>
<div id="box1">
<div id="box2"></div>
</div>
</div>
<script>
const btn = document.getElementById('btn')
const box1 = document.getElementById('box1')
btn.onclick = function(){
console.log(box1.scrollHeight)
console.log(box1.scrollWidth)
console.log(box1.offsetParent)
console.log(box1.offsetLeft)
console.log(box1.offsetTop)
console.log(box1.scrollTop)
}
</script>
</body>
除了直接修改样式外,也可以通过修改class属性来间接的修改样式
- 可以一次性修改多个样式
- 对JS和CSS进行解耦
是一个对象,对象中提供了对当前元素的类的各种操作方法
元素.classList.add() :向元素中添加一个或多个class
元素.classList.remove(): 移除元素中的一个或多个class
元素.classList.toggle() :切换元素中的class
元素.classList.replace(): 替换class
元素.classList.contains() :检查class
<style>
.box1 {
width: 200px;
height: 200px;
background-color: #bfa;
}
.box2{
background-color: yellow;
width: 300px;
height: 500px;
border: 10px greenyellow solid;
}
</style>
</head>
<body>
<button id="btn">点我一下</button>
<hr>
<div class="box1 box3 box4"></div>
<script>
//点击按钮后,修改box1的宽度
const btn = document.getElementById("btn")
const box1 = document.querySelector(".box1")
btn.onclick = function(){
//除了直接修改样式外,也可以通过修改class属性来间接的修改样式
// box1.className += 'box2'
// box1.classList.add('box2','box3','box4')
// box1.classList.add('box1')
// box1.classList.remove('box2')
box1.classList.toggle('box2')
// box1.classList.replace('box2')
let result = box1.classList.contains('box3')
console.log(result)
}
</script>
</body>
- 事件对象
- 事件对象是有浏览器在事件触发时所创建的对象, 这个对象中封装了事件相关的各种信息
- 通过事件对象可以获取到事件的详细信息 比如:鼠标的坐标、键盘的按键..
- 浏览器在创建事件对象后,会将事件对象作为响应函数的参数传递, 所以我们可以在事件的回调函数中定义一个形参来接收事件对象
<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>
#box1 {
width: 300px;
height: 300px;
border: 10px greenyellow solid;
}
</style>
</head>
<body>
<div id="box1"></div>
<script>
const box1 = document.getElementById("box1")
box1.onmousemove = event => {
console.log(event)
}
box1.addEventListener("mousemove",event => {
console.log(event.clientX,event.clientY)
box1.textContent = event.clientX + ',' + event.clientYs
})
</script>
</body>
<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>
#box1 {
width: 300px;
height: 300px;
border: 10px greenyellow solid;
}
</style>
</head>
<body>
<div id="box1"></div>
<script>
const box1 = document.getElementById("box1")
box1.onmousemove = event => {
console.log(event)
}
box1.addEventListener("mousemove",event => {
console.log(event.clientX,event.clientY)
box1.textContent = event.clientX + ',' + event.clientYs
})
</script>
</body>
在DOM中存在着多种不同类型的事件对象
- event.target 触发事件的对象
- event.currentTarget 绑定事件的对象(同this)
- event.stopPropagation() 停止事件的传导
- event.preventDefault() 取消默认行为
- 事件的冒泡就是指事件的向上传到
- 当元素上的某个事件被触发后,其祖先元素上的相同事件也会同时被触发
- 冒泡的存在大大的简化了代码的编写,但是在一些场景下我们并不希望冒泡存在 不希望事件冒泡时,可以通过事件对象来取消冒泡
在事件的响应函数中:
表示的是触发事件的对象
this 绑定事件的对象
取消事件的传导
<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>
#box1 {
width: 300px;
height: 300px;
background-color: greenyellow;
}
#box2 {
width: 250px;
height: 250px;
background-color: #ff0;
}
#box3 {
width: 200px;
height: 200px;
background-color: orange;
}
</style>
</head>
<body>
<div id="box1">
<div id="box2">
<div id="box3"></div>
</div>
</div>
<a id="chao" href="https://lilichao.com">超链接</a>
<script>
const box1 = document.getElementById("box1")
const box2 = document.getElementById("box2")
const box3 = document.getElementById("box3")
const chao = document.getElementById("chao")
chao.addEventListener('click',(event) =>{
event.preventDefault();
alert('被点了一下')
})
box1.addEventListener('click',function (event){
alert(event)
console.log(event.target)//event.target 表示的是触发事件的对象
console.log(this)//this 绑定事件的对象
console.log(event.currentTarget)
alert("hello 我是box1")
})
box2.addEventListener('click',function(event){
event.stopPropagation()
alert('我是box2')
})
box3.addEventListener('click',function(event){
event.stopPropagation()//取消事件的传导
alert('我是box3')
})
</script>
</body>
BOM
- 浏览器对象模型
- BOM为我们提供了一组对象,通过这组对象可以完成对浏览器的各种操作
- BOM对象:
- Window —— 代表浏览器窗口(全局对象)
- Navigator —— 浏览器的对象(可以用来识别浏览器)
- Location —— 浏览器的地址栏信息
- History —— 浏览器的历史记录(控制浏览器前进后退)
- Screen —— 屏幕的信息
- BOM对象都是作为window对象的属性保存的,所以可以直接在JS中访问这些对象
<script>
console.log(history)
</script>

- Navigator —— 浏览器的对象(可以用来识别浏览器)
返回一个用来描述浏览器信息的字符串
<script>
console.log(navigator.userAgent)
let sBrowser
const sUsrAg = navigator.userAgent
if (sUsrAg.indexOf("Firefox") > -1) {
sBrowser = "Mozilla Firefox"
// "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
} else if (sUsrAg.indexOf("SamsungBrowser") > -1) {
sBrowser = "Samsung Internet"
// "Mozilla/5.0 (Linux; Android 9; SAMSUNG SM-G955F Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/9.4 Chrome/67.0.3396.87 Mobile Safari/537.36
} else if (
sUsrAg.indexOf("Opera") > -1 ||
sUsrAg.indexOf("OPR") > -1
) {
sBrowser = "Opera"
// "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 OPR/57.0.3098.106"
} else if (sUsrAg.indexOf("Trident") > -1) {
sBrowser = "Microsoft Internet Explorer"
// "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Zoom 3.6.0; wbx 1.0.0; rv:11.0) like Gecko"
} else if (sUsrAg.indexOf("Edge") > -1) {
sBrowser = "Microsoft Edge (Legacy)"
// "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
} else if (sUsrAg.indexOf("Edg") > -1) {
sBrowser = "Microsoft Edge (Chromium)"
// Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64
} else if (sUsrAg.indexOf("Chrome") > -1) {
sBrowser = "Google Chrome or Chromium"
// "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/66.0.3359.181 Chrome/66.0.3359.181 Safari/537.36"
} else if (sUsrAg.indexOf("Safari") > -1) {
sBrowser = "Apple Safari"
// "Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1 980x1306"
} else {
sBrowser = "unknown"
}
alert(`You are using: ${sBrowser}`)
</script>
location 表示的是浏览器地址栏的信息
- 可以直接将location的值修改为一个新的地址,这样会使得网页发生跳转
- location.assign() 跳转到一个新的地址
- location.replace() 跳转到一个新的地址(无法通过回退按钮回退)
- location.reload() 刷新页面,可以传递一个true来强制清缓存刷新
- location.href 获取当前地址
<body>
<button id="btn">点我一下</button>
<input type="text" name="username" id="">
<script>
const btn = document.getElementById("btn")
btn.addEventListener('click',() => {
console.log(location.href)//当前地址
// location = 'https://www.lilichao.com'//使得点击按钮后,发生跳转,实现标签a的功能,通过JavaScript
// location.assign('https://www.lilichao.com')
location.replace('https://www.lilichao.com')
})
</script>
</body>
- 回退按钮
- 前进按钮
- 可以向前跳转也可以向后跳转
<body>
<button id="btn">点我一下</button>
<script>
const btn = document.getElementById('btn')
btn.onclick = () => {
console.log(history.length)
history.back()
history.forward()
history.go(-1)
}
</script>
</body>
<button id="btn">点我一下</button>
<script>
const btn = document.getElementById('btn')
btn.onclick = () => {
console.log(history.length)
history.back()
history.forward()
history.go(-1)
}
</script>
</body>
通过定时器,可以使代码在指定时间后执行
- 设置定时器的方式有两种:
- 参数:
- 回调函数(要执行的代码)
- 间隔的时间(毫秒)
- 关闭定时器
每间隔一段时间代码就会执行一次
- 参数:
- 回调函数(要执行的代码)
- 间隔的时间(毫秒)
- 关闭定时器
<body>
<h1 id="num"></h1>
<script>
// const timer = setTimeout(()=>{
// alert('我是定时器中的代码')
// },3000)//只执行一次
// clearTimeout(timer)
const numH1 = document.getElementById('num')
let num = 0
const timer = setInterval(() => {
num++
numH1.textContent = num
if(num === 200){
clearInterval(timer)
}
},3000)
</script>
</body>
<h1 id="num"></h1>
<script>
// const timer = setTimeout(()=>{
// alert('我是定时器中的代码')
// },3000)//只执行一次
// clearTimeout(timer)
const numH1 = document.getElementById('num')
let num = 0
const timer = setInterval(() => {
num++
numH1.textContent = num
if(num === 200){
clearInterval(timer)
}
},3000)
</script>
</body>
就是在指定时间后将函数添加到消息队列中
setInterval() 没间隔一段时间就将函数添加到消息队列中
但是如果函数执行的速度比较慢,它是无法确保每次执行的间隔都是一样的
<script>
console.time()
setTimeout(function(){
console.timeEnd()
console.log('定时器执行了')
},3000)
//使程序卡6s
const begin = Date.now()
while(Date.now() - begin < 6000){}
console.time("间隔")
setInterval(function(){
console.timeEnd('间隔')
console.log('定时器执行了~')
alert('定时器执行~')
console.time('间隔')
},3000)
/*
希望可以确保函数每次执行都有相同间隔
*/
// console.time("间隔")
// setTimeout(function fn() {
// console.timeEnd("间隔")
// alert("哈哈")
// console.time("间隔")
// // 在setTimeout的回调函数的最后,在调用一个setTimeout
// setTimeout(fn, 3000)
// }, 3000)
setTimeout(()=>{
console.log(11111)
}, 0)
console.log(222222)
</script>
- 函数在每次执行时,都会产生一个执行环境
- 执行环境负责存储函数执行时产生的一切数据
- 问题:函数的执行环境要存储到哪里呢?
- 函数的执行环境存储到了一个叫做调用栈的地方
- 栈,是一种数据结构,特点 后进先出
- 队列,是一种数据结构,特点 先进先出
- 调用栈负责存储函数的执行环境
- 当一个函数被调用时,它的执行环境会作为一个栈帧
插入到调用栈的栈顶,函数执行完毕其栈帧会自动从栈中弹出
```html
<script>
function fn(){
let a = 10
let b = 20
function fn2(){
console.log('fn2')
}
fn2()
console.log('fn~')
}
fn()
console.log(1111)
</script>
```
- 当一个函数被调用时,它的执行环境会作为一个栈帧
插入到调用栈的栈顶,函数执行完毕其栈帧会自动从栈中弹出
```html
<script>
function fn(){
let a = 10
let b = 20
function fn2(){
console.log('fn2')
}
fn2()
console.log('fn~')
}
fn()
console.log(1111)
</script>
```

- 队列,是一种数据结构,特点 先进先出
- 消息队列负责存储将要执行的函数
- 当我们触发一个事件时,其响应函数并不是直接就添加到调用栈中的。
- 因为调用栈中有可能会存在一些还没有执行完的代码
- 事件触发后,JS引擎是将事件响应函数插入到消息队列中排队
<body>
<button id="btn">点我一下</button>
<button id="btn02">点我一下2</button>
<script>
function fn(){
let a = 10
let b = 20
function fn2(){
console.log('fn2')
}
fn2()
console.log('fn~')
}
fn()
console.log(1111)
const btn = document.getElementById("btn")
const btn02 = document.getElementById("btn02")
btn.onclick = function(){
alert(1111)
const begin = Date.now()
while(Date.now() - begin < 3000){
}
}
btn02.onclick = function () {
alert(2222)
}
</script>
</body>
<button id="btn">点我一下</button>
<button id="btn02">点我一下2</button>
<script>
function fn(){
let a = 10
let b = 20
function fn2(){
console.log('fn2')
}
fn2()
console.log('fn~')
}
fn()
console.log(1111)
const btn = document.getElementById("btn")
const btn02 = document.getElementById("btn02")
btn.onclick = function(){
alert(1111)
const begin = Date.now()
while(Date.now() - begin < 3000){
}
}
btn02.onclick = function () {
alert(2222)
}
</script>
</body>
© 版权声明
文章版权归作者所有,未经允许请勿转载。