黑马pink JavaScript学习笔记_Web APIs Day2
事件监听(绑定)
什么是事件?
事件是系统内发生的动作或者发生的事情。比如:用户点击页面上的一个按钮。
什么是事件监听?
就是让程序检测是否有事件产生,一旦有事件触发,就立即调用一个函数做出响应,也称为注册事件
比如:鼠标经过的时候,弹出一个alert“鼠标经过了~”
语法
元素对象.addEventListener('事件类型', 要执行的函数)
事件监听三要素:
- 事件源:哪个DOM元素被触发了
- 事件类型:什么方式触发?比如:点击click, 鼠标经过mouseenter, 鼠标离开 mouseleave
- 事件调用的函数:要做什么事情
//鼠标离开,开启定时器
bigBox.addEventListener('mouseleave', function () {
//先关闭之前的定时器
clearInterval(timerId);
//再开启定时器
timerId = setInterval(function () {
next.click();
}, 1000)
})
案例:随机点名案例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
h2 {
text-align: center;
}
.box {
width: 600px;
margin: 50px auto;
display: flex;
font-size: 25px;
line-height: 40px;
}
.qs {
width: 450px;
height: 40px;
color: red;
}
.btns {
text-align: center;
}
.btns button {
width: 120px;
height: 35px;
margin: 0 50px;
}
</style>
</head>
<body>
<h2>随机点名</h2>
<div class="box">
<span>名字是:</span>
<div class="qs">这里显示姓名</div>
</div>
<div class="btns">
<button class="start">开始</button>
<button class="end">结束</button>
</div>
<script>
// 数据数组
let arr = ['马超', '黄忠', '赵云', '关羽', '张飞']
let timerId = 0;
let random = 0;
//开始按钮模块
const start = document.querySelector(".start");
const qs = document.querySelector(".qs");
start.addEventListener("click", function () {
timerId = setInterval(function () {
random = Math.floor(Math.random() * arr.length);
qs.innerHTML = arr[random];
}, 50)
if (arr.length === 1) {
start.disabled = true;
end.disabled = true;
}
})
//结束按钮模块
const end = document.querySelector(".end");
end.addEventListener('click', function () {
clearInterval(timerId);
arr.splice(random, 1);
console.log(arr);
})
</script>
</body>
</html>


事件类型
鼠标触发(鼠标事件)
- click 鼠标点击
- mouseenter 鼠标经过
- mouseleave 鼠标离开
表单获得光标(焦点事件)
- focus 获得焦点
- blur 失去焦点
键盘触发(键盘事件)
- keydown 键盘按下触发
- keyup 键盘抬起触发
表单输入触发(文本事件)
- input 用户输入事件
案例:轮播图点击切换

<!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>
* {
box-sizing: border-box;
}
.slider {
width: 560px;
height: 400px;
overflow: hidden;
}
.slider-wrapper {
width: 100%;
height: 320px;
}
.slider-wrapper img {
width: 100%;
height: 100%;
display: block;
}
.slider-footer {
height: 80px;
background-color: rgb(100, 67, 68);
padding: 12px 12px 0 12px;
position: relative;
}
.slider-footer .toggle {
position: absolute;
right: 0;
top: 12px;
display: flex;
}
.slider-footer .toggle button {
margin-right: 12px;
width: 28px;
height: 28px;
appearance: none;
border: none;
background: rgba(255, 255, 255, 0.1);
color: #fff;
border-radius: 4px;
cursor: pointer;
}
.slider-footer .toggle button:hover {
background: rgba(255, 255, 255, 0.2);
}
.slider-footer p {
margin: 0;
color: #fff;
font-size: 18px;
margin-bottom: 10px;
}
.slider-indicator {
margin: 0;
padding: 0;
list-style: none;
display: flex;
align-items: center;
}
.slider-indicator li {
width: 8px;
height: 8px;
margin: 4px;
border-radius: 50%;
background: #fff;
opacity: 0.4;
cursor: pointer;
}
.slider-indicator li.active {
width: 12px;
height: 12px;
opacity: 1;
}
</style>
</head>
<body>
<div class="slider">
<div class="slider-wrapper">
<img src="./images/slider01.jpg" alt="" />
</div>
<div class="slider-footer">
<p>对人类来说会不会太超前了?</p>
<ul class="slider-indicator">
<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div class="toggle">
<button class="prev"><</button>
<button class="next">></button>
</div>
</div>
</div>
<script>
// 1. 初始数据
const sliderData = [
{ url: './images/slider01.jpg', title: '对人类来说会不会太超前了?', color: 'rgb(100, 67, 68)' },
{ url: './images/slider02.jpg', title: '开启剑与雪的黑暗传说!', color: 'rgb(43, 35, 26)' },
{ url: './images/slider03.jpg', title: '真正的jo厨出现了!', color: 'rgb(36, 31, 33)' },
{ url: './images/slider04.jpg', title: '李玉刚:让世界通过B站看到东方大国文化', color: 'rgb(139, 98, 66)' },
{ url: './images/slider05.jpg', title: '快来分享你的寒假日常吧~', color: 'rgb(67, 90, 92)' },
{ url: './images/slider06.jpg', title: '哔哩哔哩小年YEAH', color: 'rgb(166, 131, 143)' },
{ url: './images/slider07.jpg', title: '一站式解决你的电脑配置问题!!!', color: 'rgb(53, 29, 25)' },
{ url: './images/slider08.jpg', title: '谁不想和小猫咪贴贴呢!', color: 'rgb(99, 72, 114)' },
]
const img = document.querySelector(".slider-wrapper img");
const p = document.querySelector('.slider-footer p');
const prev = document.querySelector(".prev");
const next = document.querySelector(".next");
//下一页按钮
let i = 0;
next.addEventListener('click', function () {
i++;
//重置
if (i >= sliderData.length) {
i = 0;
}
toggle();
})
//上一页按钮
prev.addEventListener('click', function () {
i--;
//重置
if (i < 0) {
i = 7;
}
toggle();
})
//自动播放
let timerId = setInterval(function () {
next.click();
}, 1000)
//鼠标经过,停止定时器
const bigBox = document.querySelector('.slider');
bigBox.addEventListener('mouseenter', function () {
clearInterval(timerId);
})
//鼠标离开,开启定时器
bigBox.addEventListener('mouseleave', function () {
//先关闭之前的定时器
clearInterval(timerId);
//再开启定时器
timerId = setInterval(function () {
next.click();
}, 1000)
})
//抽取公共方法
function toggle() {
//设置图片及标题
img.src = sliderData[i].url;
p.innerHTML = sliderData[i].title;
//设置radio
document.querySelector('.active').classList.remove('active');
document.querySelector(`.slider-indicator li:nth-child(${i + 1})`).classList.add('active');//这里注意一下,也是i+1
//设置底部背景色
document.querySelector('.slider-footer').style.backgroundColor = sliderData[i].color;
}
</script>
</body>
</html>
案例:小米搜索框

<!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>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul {
list-style: none;
}
.mi {
position: relative;
width: 223px;
margin: 100px auto;
}
.mi input {
width: 223px;
height: 48px;
padding: 0 10px;
font-size: 14px;
line-height: 48px;
border: 1px solid #e0e0e0;
outline: none;
}
.mi .search {
border: 1px solid #ff6700;
}
.result-list {
display: none;
position: absolute;
left: 0;
top: 48px;
width: 223px;
border: 1px solid #ff6700;
border-top: 0;
background: #fff;
}
.result-list a {
display: block;
padding: 6px 15px;
font-size: 12px;
color: #424242;
text-decoration: none;
}
.result-list a:hover {
background-color: #eee;
}
</style>
</head>
<body>
<div class="mi">
<input type="search" placeholder="小米笔记本">
<ul class="result-list">
<li><a href="#">全部商品</a></li>
<li><a href="#">小米11</a></li>
<li><a href="#">小米10S</a></li>
<li><a href="#">小米笔记本</a></li>
<li><a href="#">小米手机</a></li>
<li><a href="#">黑鲨4</a></li>
<li><a href="#">空调</a></li>
</ul>
</div>
<script>
//鼠标悬浮事件
const input = document.querySelector("input");
input.addEventListener('focus', function () {
input.classList.add('search');
document.querySelector('.result-list').style.display = 'block';
});
//鼠标离开事件
input.addEventListener('blur', function () {
input.classList.remove('search');
document.querySelector('.result-list').style.display = 'none';
});
</script>
</body>
</html>


案例:评论字数统计

<!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 {
min-width: 400px;
max-width: 800px;
display: flex;
justify-content: flex-end;
}
.avatar {
width: 48px;
height: 48px;
border-radius: 50%;
overflow: hidden;
background: url(./images/avatar.jpg) no-repeat center / cover;
margin-right: 20px;
}
.wrapper textarea {
outline: none;
border-color: transparent;
resize: none;
background: #f5f5f5;
border-radius: 4px;
flex: 1;
padding: 10px;
transition: all 0.5s;
height: 30px;
}
.wrapper textarea:focus {
border-color: #e4e4e4;
background: #fff;
height: 50px;
}
.wrapper button {
background: #00aeec;
color: #fff;
border: none;
border-radius: 4px;
margin-left: 10px;
width: 70px;
cursor: pointer;
}
.wrapper .total {
margin-right: 80px;
color: #999;
margin-top: 5px;
opacity: 0;
transition: all 0.5s;
}
.list {
min-width: 400px;
max-width: 800px;
display: flex;
}
.list .item {
width: 100%;
display: flex;
}
.list .item .info {
flex: 1;
border-bottom: 1px dashed #e4e4e4;
padding-bottom: 10px;
}
.list .item p {
margin: 0;
}
.list .item .name {
color: #FB7299;
font-size: 14px;
font-weight: bold;
}
.list .item .text {
color: #333;
padding: 10px 0;
}
.list .item .time {
color: #999;
font-size: 12px;
}
</style>
</head>
<body>
<div class="wrapper">
<i class="avatar"></i>
<textarea id="tx" placeholder="发一条友善的评论" rows="2" maxlength="200"></textarea>
<button>发布</button>
</div>
<div class="wrapper">
<span class="total">0/200字</span>
</div>
<div class="list">
<div class="item" style="display: none;">
<i class="avatar"></i>
<div class="info">
<p class="name">清风徐来</p>
<p class="text">大家都辛苦啦,感谢各位大大的努力,能圆满完成真是太好了[笑哭][支持]</p>
<p class="time">2022-10-10 20:29:21</p>
</div>
</div>
</div>
<script>
const tx = document.querySelector('#tx');
const total = document.querySelector('.total');
tx.addEventListener('focus', function () {
total.style.opacity = 1;
})
tx.addEventListener('blur', function () {
total.style.opacity = 0;
})
tx.addEventListener('input', function () {
total.innerHTML = `${tx.value.length}/200字`;
})
</script>
</body>
</html>

事件对象
事件对象是什么
事件对象也是一个对象,里面有事件触发的相关信息。
如:鼠标点击事件中,事件对象就存储了鼠标点在哪个位置的信息。
使用场景:
- 可以判断用户按下了哪个按键,不同的按键走不同的代码逻辑
获取事件对象
语法:事件绑定的回调函数的第一个参数就是事件对象。

事件对象常用属性
- type
- 获取当前的事件类型
- clientX/clientY
- 获取当前光标相对于浏览器可视窗口左上角的位置
- offsetX/offsetY
- 获取光标相对于当前DOM元素左上角的位置
- key
- 获取用户按下的键盘键的值
- 使用key,现在不提倡使用keyCode
案例:按下回车键,发布评论信息

<!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 {
min-width: 400px;
max-width: 800px;
display: flex;
justify-content: flex-end;
}
.avatar {
width: 48px;
height: 48px;
border-radius: 50%;
overflow: hidden;
background: url(./images/avatar.jpg) no-repeat center / cover;
margin-right: 20px;
}
.wrapper textarea {
outline: none;
border-color: transparent;
resize: none;
background: #f5f5f5;
border-radius: 4px;
flex: 1;
padding: 10px;
transition: all 0.5s;
height: 30px;
}
.wrapper textarea:focus {
border-color: #e4e4e4;
background: #fff;
height: 50px;
}
.wrapper button {
background: #00aeec;
color: #fff;
border: none;
border-radius: 4px;
margin-left: 10px;
width: 70px;
cursor: pointer;
}
.wrapper .total {
margin-right: 80px;
color: #999;
margin-top: 5px;
opacity: 0;
transition: all 0.5s;
}
.list {
min-width: 400px;
max-width: 800px;
display: flex;
}
.list .item {
width: 100%;
display: flex;
}
.list .item .info {
flex: 1;
border-bottom: 1px dashed #e4e4e4;
padding-bottom: 10px;
}
.list .item p {
margin: 0;
}
.list .item .name {
color: #FB7299;
font-size: 14px;
font-weight: bold;
}
.list .item .text {
color: #333;
padding: 10px 0;
}
.list .item .time {
color: #999;
font-size: 12px;
}
</style>
</head>
<body>
<div class="wrapper">
<i class="avatar"></i>
<textarea id="tx" placeholder="发一条友善的评论" rows="2" maxlength="200"></textarea>
<button>发布</button>
</div>
<div class="wrapper">
<span class="total">0/200字</span>
</div>
<div class="list">
<div class="item" style="display: none;">
<i class="avatar"></i>
<div class="info">
<p class="name">清风徐来</p>
<p class="text">大家都辛苦啦,感谢各位大大的努力,能圆满完成真是太好了[笑哭][支持]</p>
<p class="time">2022-10-10 20:29:21</p>
</div>
</div>
</div>
<script>
const tx = document.querySelector('#tx');
const total = document.querySelector('.total');
const text = document.querySelector('.text');
tx.addEventListener('focus', function () {
total.style.opacity = 1;
})
tx.addEventListener('blur', function () {
total.style.opacity = 0;
})
tx.addEventListener('input', function () {
total.innerHTML = `${tx.value.length}/200字`;
})
tx.addEventListener('keyup', function (e) {
if (e.key == 'Enter') {
if (tx.value.trim() !== '') {
document.querySelector('.item').style.display = 'block';
text.innerHTML = tx.value.trim();
}
tx.value = '';
}
})
</script>
</body>
</html>

环境对象
概念:环境对象指的是函数内部特殊的变量this,它代表当前函数运行时所处的环境。
粗略理解:谁调用函数,this指向的就是谁。
回调函数
概念:将函数A作为参数传递给函数B,这个时候,我们就把函数A称为“回调函数”
回调函数的本质还是函数,只不过把它当参数使用。
tx.addEventListener('input', function () {
console.log("我是一个回调函数");
})
综合案例:Tab栏切换
鼠标经过不同的选项卡,下面动态显示不同的内容。
<!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>tab栏切换</title>
<style>
* {
margin: 0;
padding: 0;
}
.tab {
width: 590px;
height: 340px;
margin: 20px;
border: 1px solid #e4e4e4;
}
.tab-nav {
width: 100%;
height: 60px;
line-height: 60px;
display: flex;
justify-content: space-between;
}
.tab-nav h3 {
font-size: 24px;
font-weight: normal;
margin-left: 20px;
}
.tab-nav ul {
list-style: none;
display: flex;
justify-content: flex-end;
}
.tab-nav ul li {
margin: 0 20px;
font-size: 14px;
}
.tab-nav ul li a {
text-decoration: none;
border-bottom: 2px solid transparent;
color: #333;
}
.tab-nav ul li a.active {
border-color: #e1251b;
color: #e1251b;
}
.tab-content {
padding: 0 16px;
}
.tab-content .item {
display: none;
}
.tab-content .item.active {
display: block;
}
</style>
</head>
<body>
<div class="tab">
<div class="tab-nav">
<h3>每日特价</h3>
<ul>
<li><a class="active" href="javascript:;">精选</a></li>
<li><a href="javascript:;">美食</a></li>
<li><a href="javascript:;">百货</a></li>
<li><a href="javascript:;">个护</a></li>
<li><a href="javascript:;">预告</a></li>
</ul>
</div>
<div class="tab-content">
<div class="item active"><img src="./images/tab00.png" alt="" /></div>
<div class="item"><img src="./images/tab01.png" alt="" /></div>
<div class="item"><img src="./images/tab02.png" alt="" /></div>
<div class="item"><img src="./images/tab03.png" alt="" /></div>
<div class="item"><img src="./images/tab04.png" alt="" /></div>
</div>
</div>
<script>
const as = document.querySelectorAll('a');
for (let i = 0; i < as.length; i++) {
as[i].addEventListener('mouseenter', function () {
// console.log('hello');
document.querySelector('.tab-nav .active').classList.remove('active');
this.classList.add('active');
document.querySelector('.tab-content .active').classList.remove('active');
document.querySelector(`.tab-content .item:nth-child(${i + 1})`).classList.add('active');
})
}
</script>
</body>
</html>
·

浙公网安备 33010602011771号