目录
作用
操作浏览器和html。
bom --- 浏览器对象模型,整个浏览器页面就是bom;bom包含DOM,navigator,location,history,screen。
DOM --- 页面文档对象模型
获取元素
通过CSS选择器获取
document.querySelector(`CSS选择器`)
let x= document.querySelector(`CSS选择器`)//使用
document.querySelector只获取满足条件的第一个。
获取所有满足条件的数据:
document.querySelectorAll(`CSS选择器`)
class名
document.document.getElementsByClassName(`class名`)
let x= document.getElementsByClassName(`class名`)
标签名
document.getElementsByTagName(`标签名`)
let x= document.getElementsByTagName(`标签名`)
id名
document.getElementById(`id`)
let x= document.getElementById(`id`)
推荐使用CSS选择器进行获取。
修改元素内容
innerText(不能识别标签)
<body>
<div>长风破浪会有时</div>
<script src="./练习.js"></script>
</body>
let div =document.querySelector(`div`)
div.innerText=`直挂云帆济沧海`
innerHtml(能识别标签)
let div =document.querySelector(`div`)
div.innerHTML=`<h1>qwertyu<h1>`
修改元素属性
格式:元素.属性名=属性值
例如:
<body>
<img src="./小熊.png" alt="" title="白熊">
<script src="./练习.js"></script>
</body>
let img=document.querySelector(`img`)
img.title=`奔跑的白熊`
补充:只要是属性,都可以更改。
修改元素样式
例如:
div {
width: 200px;
height: 200px;
background-color: aqua;
}
通过style操作
const box = document.querySelector(`div`)
box.style.backgroundColor = 'pink'
box.style.width=`300px`
以此类推。
通过操作class名更改样式
<body>
<div class="x"></div>
<div class="y"></div>
<script src="./练习.js"></script>
</body>
.x {
width: 200px;
height: 200px;
background-color: aqua;
}
.y {
width: 400px;
height: 500px;
background-color: blue;
}
.pink {
width: 100px;
height: 100px;
background-color: pink;
}
将类pink覆盖在类x上(会删除原来的类名):
const box1=document.querySelector(`.x`)
box1.className=`pink`
添加类名,保留原来的类名(覆盖相同标签的内容,不相同的标签内容保留):
const box1=document.querySelector(`.x`)
box1.classList.add(`pink`)
移除类名:
const box1=document.querySelector(`.x`)
box1.classList.remove(`x`)
识别添加或移除(若有指定类名,则删除;若无,则添加):
const box1=document.querySelector(`.x`)
box1.classList.toggle(`x`)//识别类名
修改设置表单元素
<body>
<form action="">
<input type="text">
</form>
<script src="./练习.js"></script>
</body>
let x = document.querySelector(`input`)
x.type=`password`
事件监听
程序检测某事件有没有发生,一旦发生,立刻调用一个函数作响应。(触发一次执行一次)
语法:元素.addEventListener('事件',执行的函数(冒泡或捕捉))
常见事件类型
点击事件 --- click
<body>
<button>显示</button>
<button>隐藏</button>
<div></div>
<script src="./练习.js"></script>
</body>
示例:
函数不被括号包括。
const x=document.querySelector(`button:nth-child(1)`)
const y=document.querySelector(`button:nth-child(2)`)
x.addEventListener(`click`,function(){
console.log(`hello`);
})
加载事件
JavaScript开发时默认将window这个函数放在顶层。(首先加载)
代码运行时默认是从上到下,若将JavaScript代码写在作用对象的前面,无疑会报错:
<!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>
<link rel="stylesheet" href="./练习.css">
<script src="./练习.js"></script>
</head>
<body>
<button>显示</button>
<button>隐藏</button>
<div></div>
</body>
</html>
const x=document.querySelector(`button:nth-child(1)`)
const y=document.querySelector(`button:nth-child(2)`)
x.addEventListener(`click`,function(){
console.log(`hello`);
})
将其写在window里:
window.addEventListener(`load`,function(){
const x=document.querySelector(`button:nth-child(1)`)
const y=document.querySelector(`button:nth-child(2)`)
x.addEventListener(`click`,function(){
console.log(`hello`);
})
})
获取焦点与失去焦点 --- focus&blur
<body>
<input type="text">
<script src="./练习.js"></script>
</body>
在获取焦点(输入状态)后文本框变为粉色,失去焦点后文本框变为蓝色:
const x = document.querySelector(`input`)
x.addEventListener(`focus`, function () {
x.style.backgroundColor = `pink`
})
x.addEventListener(`blur`, function () {
x.style.backgroundColor = `blue`
})
滚动事件 --- scroll
划出页面的多少。
window.addEventListener(`scroll`,function(){
console.log(document.documentElement.scrollTop);
})
document.documentElement.scrollTop//获取距离顶部的距离
可通过设置scrollTop的值来去到页面的某一个位置。(回到顶部)
其他
页面尺寸变化事件 --- resize
鼠标经过 --- mouseenter
鼠标离开 --- mouseleave
键盘按下或弹出 --- keydown/keyup
事件对象
记录事件触发的相关信息。
记录键盘按下的相关信息:
window.addEventListener(`keydown`,function(e){
console.log(e);
})
指定按键触发事件:
window.addEventListener(`keydown`,function(e){
console.log(e)
if(e.key===`Enter`){
console.log(`hello`);
}
})
事件绑定
与事件监听相似:
<body>
<button>显示</button>
<div></div>
<script src="./练习.js"></script>
</body>
div {
display: none;
width: 200px;
height: 200px;
background-color: aqua;
}
const box = document.querySelector(`div`)
const b = document.querySelector(`button`)
b.onclick = function () {
box.style.display = `block`
}
点击显示:
捕获和冒泡
捕获:从上到下一层一层执行。
冒泡:从下到上一层一层执行。
示例:
<body>
<div class="grandfather">
<div class="father">
<div class="son"></div>
</div>
</div>
<script src="./练习.js"></script>
</body>
.son {
width: 200px;
height: 200px;
background-color: aqua;
}
.father {
width: 400px;
height: 400px;
background-color: blue;
}
.grandfather {
width: 600px;
height: 600px;
background-color:pink;
}
const x=document.querySelector(`.grandfather`)
const y=document.querySelector(`.father`)
const z=document.querySelector(`.son`)
x.addEventListener(`click`,function(){
alert(`123`)
})
y.addEventListener(`click`,function(){
alert(`456`)
})
z.addEventListener(`click`,function(){
alert(`789`)
})
addEventListener后面有三个值,第三个值默认为false(冒泡)。
点击.son的框将会依次弹出.father和.grandfather的框。
表明y.addEventListener(`click`,function(){alert(`456`)},(这里默认为false))
将其改为true便会从.grandfather捕获到.son。
通过事件对象阻止捕获或者冒泡行为:
const x=document.querySelector(`.grandfather`)
const y=document.querySelector(`.father`)
const z=document.querySelector(`.son`)
x.addEventListener(`click`,function(e){
alert(`123`)
e.stopPropagation()//阻止
},true)
y.addEventListener(`click`,function(e){
alert(`456`)
e,stopPropagation()
},true)
z.addEventListener(`click`,function(e){
alert(`789`)
e.stopPropagation()
},true)
查找节点
通过father找son:
<body>
<div class="father">
<div class="son">1</div>
<div class="son">2</div>
<div class="son">3</div>
<div class="son">4</div>
</div>
<script src="./练习.js"></script>
</body>
const x=document.querySelector(`.father`)
console.log(x.children);
也可以通过数组下标锁定某一个son。
查找子节点:父元素.children【n】
通过x.childNodes查找:不仅仅会查找结点,还会查找文本,空格。
查找父节点:子节点.parentNode
const x=document.querySelector(`.father`)
console.log(x.parentNode);
查找兄弟节点:
下一个:x.nextElementSibling
上一个:x.previousElementSibling
克隆节点
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script src="./练习.js"></script>
</body>
const x=document.querySelector(`ul`)
console.log(x.cloneNode(true));//属性值代表是否将子节点一起克隆
节点创建与追加
<body>
<ul>
</ul>
<script src="./练习.js"></script>
</body>
创建并插入:
const x=document.querySelector(`ul`)//获取
let li=document.createElement(`li`)//创建
li.innerHTML=`123`//给创建的li加入内容
x.append(li)//插入到父元素的对后一个位置
向指定位置插入:
x.insertBefore(插入元素,插入位置);插入到指定位置的前面。
例如: x.insertBefore(li,children[n])
删除节点
一定是通过父元素删除的。
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li class="four">4</li>
<li>5</li>
</ul>
<script src="./练习.js"></script>
</body>
const x=document.querySelector(`ul`)
const y=document.querySelector(`.four`)
x.removeChild(y)
执行后:
定时器
setTimeout
某个函数或者某个代码在多少毫秒后执行,会返回一个整数(编号)用来标记定时器。
const x=setTimeout(function(){
alert(`hello`)
},2000)//单位是毫秒
2s后显示:
打印一下返回值:
console.log(x);
它不仅仅可以写函数,也可以执行代码(字符串格式)。
例如:
const x=setTimeout("alert(`hello`)",2000)//字符串格式
console.log(x);
它可以有多个参数:
const x=setTimeout(function(a,b){
console.log(a+b);
},2000,1,2)//后面两个数将在计时结束后作为参数传入函数
setInterval
函数或者代码,每隔一段时间再执行一次;用法与上面那个相似。
const x=setInterval("console.log(`hello`)",2000);
console.log(x);
删除定时器
使用setTimeout生成的定时器:
clearTimeout(x)//定时器名称
使用 setInterval生成的定时器:
clearInterval(x)//定时器名称
事件委托
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script src="./练习.js"></script>
</body>
const ul=document.querySelector(`ul`)//获取元素
ul.addEventListener(`click`,function(e){
e.target.style.backgroundColor=`blue`//使用事件对象来锁定点击目标
})
点击哪个哪个背景颜色变化:
箭头函数
1、简化代码
2、解决this问题
一般应用在回调函数及函数表达式中。
基本语法:()=>{}
例如:
const fn=(x,y)=>{
console.log(x+y);
}
fn(22,33)
当函数只有一个参数时,()可以省略:
const fn=x=>{
console.log(x);
}
fn(22)
当只有一行代码时,{}和return可以省略:
const fn=x=>console.log(x);
fn(2)
直接返回对象:
const fn=()=>({name:`1234`})//括号一定要
this指向
console.log(this);
全局下默认时候this指向window:
在函数中默认指向window(函数是通过window调用;函数都是在window上写的;函数谁调用就指向谁):
function fn() {
console.log(this);
}
fn()
事件监听里的this指向事件源:
<body>
<button>启动</button>
<script src="./练习.js"></script>
</body>
let but=document.querySelector(`button`)
but.addEventListener(`click`,function(){
console.log(this);
this.style.backgroundColor=`blue`
})
对象方法中的this指向对象本身:
let obj={
a:1,
y:2,
z:function(){
console.log(this);
}
}
obj.z()
定时器中的this指向window:
setTimeout('console.log(this)',2000)
//本质上:window.setTimeout('console.log(this)',2000)
箭头函数中的this:箭头函数中没有this的作用域;箭头函数不会创建自己的this,只会继承上一级的this,上面没有就指向window。
构造函数中的this指向构造函数创建的实例化。
注意:避免使用多层this。
补充:所有通过var定义的全局变量、函数都会变成window的属性和方法,window对象下的属性方法,调用时都可以省略window。
JavaScript执行机制
同步任务:一件事一件事的做,一件事情没做完,不去执行下一个任务。程序的执行顺序与任务的排列顺序是一致的、同步的。在主线程上执行,形成执行栈。
异步任务:在做耗费时间常的事情的同时去做别的事情。通过回调函数实现的,添加到任务队列
事件、资源加载、定时器……
JavaScript是单线程,即同一时间只能做一件事情。
执行机制:
1、先执行执行栈中的同步任务(主车道)。
2、异步任务放入任务队列(应急车道)。
3、当执行栈中的同步任务执行完毕,系统会按次序读取任务队列中的异步任务,将其放入执行栈中。
4、来回反复(事件循环)。
location
保存url地址的各个组成部分。
Location
对象提供以下属性:
-
Location.href
:整个 URL。 -
Location.protocol
:当前 URL 的协议,包括冒号(:
)。 -
Location.host
:主机。如果端口不是协议默认的80
和433
,则还会包括冒号(:
)和端口。 -
Location.hostname
:主机名,不包括端口。 -
Location.port
:端口号。 -
Location.pathname
:URL 的路径部分,从根路径/
开始。 -
Location.search
:查询字符串部分,从问号?
开始。 -
Location.hash
:片段字符串部分,从#
开始。 -
Location.username
:域名前面的用户名。 -
Location.password
:域名前面的密码。 -
Location.origin
:URL 的协议、主机名和端口。(只读)
补充:reload()
刷新当前页面 传入参数true
表示强制刷新
navigator对象
反馈浏览器信息:
console.log(navigator.userAgent)
补充:
//检测移动端和pc端进行页面跳转
const userAgent = navigator.userAgent
// 验证是否是移动端
const android = userAgent.match(/(Android);?[\s\/]+([\d.]+)?/)
const iphone = userAgent.match(/(iPhone\sOS)\s([\d_]+)/)
if (android || iphone) {
location.href = 'https://www.baidu.com'
}
history对象
管理历史记录
back()
:可以后退功能
forword()
:前进功能
go()
:1:前进一个页面 -1:后退一个页面
例如:
history.forward()
stroge 接口
用于在浏览器中保存数据。
localStorage:一直储存在浏览器里。
sessionStorage:用于浏览器的一次会话,会话结束,数据清空。
方法:
setItem()
:存入数据,两个参数,键名,键值 无返回值 两个参数都是字符串,如果不是,会自动转换为字符串存储进浏览器
如果存储空间满了,会抛出错误
getItem()
:读取数据,只有一个参数,就是键名。若不存在,返回null。键名是字符串
removeItem()
:清除某个键名对应的键值。键名不存在,不返回任何的值。
clear()
:清除所有保存的数据,该方法的返回值是undefined
key()
:接受一个整数作为参数(从0开始,返回该位置的键名)