00.总结图
01.获取DOM元素
- 语法:document.querySelector( ' css选择器 ' )
- document.querySelector:匹配第一个元素对象,没有找到则返回 null
- document.querySelectorAll 返回伪数组,找不到则返回空伪数组(有长度有索引号的数组,但是没有 pop() push() 等数组方法,想要得到里面的每一个对象,则需要遍历(for)的方式获得)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box">我是一个div</div>
<ol>
<li>我是第一个孩子</li>
<li>我是第二个孩子</li>
<li>我是第三个孩子</li>
</ol>
<ul class="nav">
<li>新闻</li>
<li>体育</li>
<li>娱乐</li>
</ul>
<script>
// document.querySelector('CSS 选择器') : 匹配第一个元素对象,没有找到则返回 null
const ls = document.querySelector('.box1')
console.log(ls)
// 如果有多个标签,只找第一个
const li = document.querySelector('ol li')
console.log(li)
// querySelectorAll 返回伪数组,找不到则返回空伪数组
const lis = document.querySelectorAll('.nav li')
console.log(lis)
lis.forEach((el, index) => {
console.log(el, index)
})
</script>
</body>
</html>
02.操作元素内容
- .innerText — 不解析标签
- .innerHTML — 解析标签 → 代表解析字符中自带的标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box">这是一个div</div>
<script>
const str = document.querySelector('.box')
// innerText:不解析标签
str.innerText = '<h1>这是一个div</h1>'
// innerHTML:解析标签 → 代表解析字符中自带的标签
str.innerHTML = '这是一个div'
str.innerHTML = '<h1>这是一个div</h1>'
</script>
</body>
</html>
03.案例 - 年会抽奖
<!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>年会抽奖</title>
<style>
.wrapper {
width: 840px;
height: 420px;
background: url(./images/bg01.jpg) no-repeat center / cover;
padding: 100px 250px;
box-sizing: border-box;
}
.wrapper span {
color: #b10e0d;
}
</style>
</head>
<body>
<div class="wrapper">
<strong>年会抽奖</strong>
<h1>一等奖:<span class="one">???</span></h1>
<h3>二等奖:<span class="two">???</span></h3>
<h5>三等奖:<span class="three">???</span></h5>
</div>
<script>
// 数组
const arr = ['迪丽热巴', '古丽扎娜', '佟丽丫丫', '马尔扎哈']
// 1.定义随机数
let oneNum = Math.floor(Math.random()*arr.length)
// 2.把结果输出至页面类标签里面
document.querySelector('.one').innerHTML = arr[oneNum]
// 3. 定义随机后删除随机出来的名字 (防止后期奖项再次出现)
arr.splice(oneNum,1)
console.log(arr)
// 二等奖
let twoNum = Math.floor(Math.random()*arr.length)
// 2.把结果输出至页面类标签里面
document.querySelector('.two').innerHTML = arr[twoNum]
// 3. 定义随机后删除随机出来的名字 (防止后期奖项再次出现)
arr.splice(twoNum,1)
console.log(arr)
// 三等奖
let threeNum = Math.floor(Math.random()*arr.length)
// 2.把结果输出至页面类标签里面
document.querySelector('.three').innerHTML = arr[threeNum]
// 3. 定义随机后删除随机出来的名字 (防止后期奖项再次出现)
arr.splice(threeNum,1)
console.log(arr)
</script>
</body>
</html>
04.事件监听
- 语法:元素对象.addEventListener('事件类型',事件处理函数)
事件三要素:
- 哪个元素上触发?→ button等 → 事件源
- 什么情况下触发?→ 鼠标单击 click、鼠标