一、事件监听
事件是系统运行时发生的动作或者发生的事情
1.1 事件监听
元素对象.addEventListener('事件类型',要执行的函数)
三要素:
事件源--获取被触发的dom元素
事件类型--触发方式(比如click/mouseover)
事件调用函数--触发了做什么事
案例-随机点名
<!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>
*{
margin: 0;
padding: 0;
}
.box{
width: 500px;
height: 300px;
margin: 50px auto;
background-color: rgba(255,192,203,0.4);
border: 1px dotted #333;
border-radius: 10px;
}
h2{
margin-top: 20px;
text-align: center;
}
.txt span{
margin-top: 50px;
display: inline-block;
font-size: 18px;
padding-left: 40px;
}
.btn{
margin-top: 100px;
margin-left: 250px;
transform: translate(-50%,0);
}
.btn button{
display: inline-block;
width: 100px;
height: 30px;
margin-right: 20px;
background-color: deepskyblue;
font-weight: 600;
text-align: center;
line-height: 30px;
font-size: 18px;
color: #fff;
border-radius: 3px;
border: none;
}
.btn button:hover{
background-color: dodgerblue;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box">
<h2>随机点名</h2>
<div class="txt">
<span>名字是:</span>
<span class="name"></span>
</div>
<div class="btn">
<button class="start">开始</button>
<button class="end">停止</button>
</div>
</div>
<script>
const arr = ['马超','黄忠','赵云','关羽','张飞','曹操','项羽','程咬金']
const start = document.querySelector('.start')
const end = document.querySelector('.end')
let timeId = 0
// start.addEventListener('click',function(){
// const random = parseInt(Math.random()*arr.length)
// const name = document.querySelector('.name')
// name.innerHTML = arr[random]
// })
start.addEventListener('click',function(){
timeId = setInterval(function(){
const random = parseInt(Math.random()*arr.length)
const name = document.querySelector('.name')
name.innerHTML = arr[random]
},200)
})
end.addEventListener('click',function(){
clearInterval(timeId)
})
</script>
</body>
</html>
1.2 事件监听版本
//DOM L0
事件源.on事件 = function(){}
//DOM L2
事件源.addEventListener(事件, 事件处理函数)
//on的方式多次写入被覆盖,add可以绑定多次拥有更多特性
二、事件类型
2.1 鼠标事件
click 鼠标点击
mouseenter 鼠标经过
mouseleave 鼠标离开
终极版轮播图
<!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;
/* transition: all 1s; */
}
.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="./image/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: './image/slider01.jpg', title: '对人类来说会不会太超前了?', color: 'rgb(100, 67, 68)' },
{ url: './image/slider02.jpg', title: '开启剑与雪的黑暗传说!', color: 'rgb(43, 35, 26)' },
{ url: './image/slider03.jpg', title: '真正的jo厨出现了!', color: 'rgb(36, 31, 33)' },
{ url: './image/slider04.jpg', title: '李玉刚:让世界通过B站看到东方大国文化', color: 'rgb(139, 98, 66)' },
{ url: './image/slider05.jpg', title: '快来分享你的寒假日常吧~', color: 'rgb(67, 90, 92)' },
{ url: './image/slider06.jpg', title: '哔哩哔哩小年YEAH', color: 'rgb(166, 131, 143)' },
{ url: './image/slider07.jpg', title: '一站式解决你的电脑配置问题!!!', color: 'rgb(53, 29, 25)' },
{ url: './image/slider08.jpg', title: '谁不想和小猫咪贴贴呢!', color: 'rgb(99, 72, 114)' },
]
const img = document.querySelector('.slider-wrapper img')
const p = document.querySelector('.slider-footer p')
const footer = document.querySelector('.slider-footer')
let i = 0 //控制播放的图片顺序
//1 右侧按钮业务
const next = document.querySelector('.next')
next.addEventListener('click',function(){
i++
if(i >= 8)i = 0
toggle()
})
//2 左侧按钮业务
const prev = document.querySelector('.prev')
prev.addEventListener('click',function(){
i--
if(i < 0)i = i + sliderData.length
toggle()
})
function toggle(){
img.src = sliderData[i].url
p.innerHTML = sliderData[i].title
footer.style.backgoundColor = sliderData[i].color
document.querySelector('.slider-indicator .active').classList.remove('active')
document.querySelector(`.slider-indicator li:nth-child(${i+1})`).classList.add('active')
}
//3 自动播放
let timeId = setInterval(function(){
//利用js自动调用点击事件
next.click()
},2000)
//4 鼠标经过大盒子 停止定时器
const slider = document.querySelector('.slider')
slider.addEventListener('mouseenter',function(){
clearInterval(timeId)
})
//5 鼠标离开 继续播放
slider.addEventListener('mouseleave',function(){
clearInterval(timeId)
timeId = setInterval(function(){
//利用js自动调用点击事件
next.click()
},2000)
})
</script>
</body>
</html>
2.2 焦点事件-表单获得光标
focus 获得焦点
blur 失去焦点
小米搜索框
<!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('[type=search]')
const ul = document.querySelector('.result-list')
input.addEventListener('focus',function(){
ul.style.display = 'block'
input.classList.add('search')
})
input.addEventListener('blur',function(){
ul.style.display = 'none'
input.classList.remove('search')
})
</script>
</body>
</html>
2.3 键盘事件
keydown键盘按下触发
keyup 键盘抬起触发
2.4 文本事件
input 用户输入触发
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字`
})
三、事件对象
包含事件触发时相关信息的对象,比如用户按下哪个键、鼠标点击哪个元素
3.1 获取事件对象
//事件绑定的回调函数的第一个参数就是事件对象
//e就是事件对象
元素.addEventListener('click',function(e){
})
3.2 事件对象常用属性
type | 获取当前的事件类型 |
clientX/clientY | 获取光标相对于浏览器左上角的位置 |
offsetX/offsetY | 获取光标相对于当前DOM元素左上角的位置 |
key | 用户按下键盘键的值 |
案例-评论发布
<!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 item = document.querySelector('.item')
const text = document.querySelector('.text')
const bt = document.querySelector('.wrapper button')
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字`
})
function addComment(){
//如果用户输入的不是纯空格
//trim()去除字符串左右的空格
if(tx.value.trim()!==''){
item.style.display = 'block'
text.innerHTML = tx.value
}
//清空文本域
tx.value = ''
total.innerHTML = `0/200字`
}
//按下回车发布评论
tx.addEventListener('keyup',function(e){
if(e.key === 'Enter'){
addComment()
}
})
bt.addEventListener('click',function(){
addComment()
})
</script>
</body>
</html>
四、环境对象
this--当前函数运行时所处的环境
普通函数中this指向window
谁调用,this指向谁
五、回调函数
当一个函数做参数传递给另一个函数时,这个函数是回调函数
综合案例 -- 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="./image/tab00.png" alt="" /></div>
<div class="item"><img src="./image/tab01.png" alt="" /></div>
<div class="item"><img src="./image/tab02.png" alt="" /></div>
<div class="item"><img src="./image/tab03.png" alt="" /></div>
<div class="item"><img src="./image/tab04.png" alt="" /></div>
</div>
</div>
<script>
const as = document.querySelectorAll('.tab-nav a')
for(let i = 0; i < as.length; i++){
as[i].addEventListener('mouseenter',function() {
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>
补充--this的5种情况
1当在全局作用域中使用 this,它将指向全局对象(在浏览器中是 window 对象,在 Node.js 环境中是 global 对象)
2函数被直接调用时,this指向全局对象;当函数作为对象的方法被调用时,this 将指向调用该方法的对象
3当函数用作构造函数来创建对象时,this 指向新创建的对象。
4箭头函数的this继承其父作用域。
5基于Function.prototype上的 apply 、 call 和 bind 调用模式,这三个方法都可以显式的指定调用函数的 this 指向
//2直接调用this与在对象的方法中调用this
// 全局环境下
console.log(this); // 输出: Window
// 函数被直接调用,this指向全局对象
function globalFunction() {
console.log(this);
}
globalFunction(); // 输出: Window
// 对象方法调用,this指向调用该方法的对象
const obj = {
name: 'John',
greet: function() {
console.log(`Hello, ${this.name}!`);
}
};
obj.greet(); // 输出: Hello, John!
// 3 构造函数创建对象时的this
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
};
}
// 使用构造函数创建对象
const person1 = new Person('John', 25);
const person2 = new Person('Sarah', 30);
person1.greet(); // 输出: Hello, my name is John and I'm 25 years old.
person2.greet(); // 输出: Hello, my name is Sarah and I'm 30 years old.
//5 使用apply() 显式指定this指向
function greet(message) {
console.log(`${message}, ${this.name}!`);
}
const person = {
name: 'John'
};
//apply函数接受两个参数,一个是this要绑定的目标对象;一个是传递给函数的参数(数组或类数组)
greet.apply(person, ['Hello']); // 输出: Hello, John!
//call函数与apply类似,但传递给函数的参数是逐个列举,不是数组
greet.call(person, 'Hi'); // 输出: Hi, John!
//bind则是在绑定好this对象之后返回一个新函数,新函数中this与目标对象绑定
const greetPerson = greet.bind(person, '你好');
greetPerson(); // 输出: 你好, John!