事件监听
事件监听:让程序检测是否有事件产生,一旦有事件触发,就调用一个函数做出响应,也称为绑定事件或注册事件
事件:编程系统内发生的动作或发生的事情
比如用户单击一个按钮下拉菜单
添加事件监听
事件监听三要素:
事件源:哪个dom元素被事件触发了,要获取dom元素
事件类型:用什么方式触发的?例如鼠标单击click、鼠标经过mouseover等
事件调用的函数:事件处理程序,要做什么事
感觉有点像线程。。也有点像伪类选择器
写一个关闭小广告的案例:
<!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>
.box {
position: relative;
height: 400px;
width: 400px;
background-color: aquamarine;
margin: 10px auto;
}
.box1{
position: absolute;
right: 20px;
top: 10px;
width: 20px;
height: 20px;
background-color: skyblue;
text-align: center;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box">
我是广告
<botton class="box1">
X
</botton>
</div>
<script>
const box1=document.querySelector('.box1')
const box = document.querySelector('.box')
box1.addEventListener('click',function(){
box.style.display='none'
})
</script>
</body>
</html>
随机点名:
js部分:
const arrName = ['励志轩', '荷叶饭', '来上课', '好耶', '产业化', '雷阵雨', '蚊子咬']
const start = document.querySelector('.start')
start.addEventListener('click', function () {
const random = parseInt((Math.random() * arrName.length))
console.log(arrName[random]);
})
验证一下:
再写一个监听end按钮的事件监听
<!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>
h2 {
text-align: center;
}
.box {
width: 600px;
margin: 50px auto;
display: flex;
font-size: 25px;
line-height: 40px;
flex-direction: row;
flex-wrap: wrap;
}
.qs {
width: 450px;
height: 40px;
color: lightcoral;
}
.btn {
text-align: center;
}
.btn button {
width: 120px;
height: 35px;
margin: 0 50px;
}
</style>
</head>
<body>
<h2>随机点名</h2>
<div class="box">
<span>名字是:</span>
<div class="qs">这里显示姓名</div>
<div class="btn">
<button class="start">开始</button>
<button class="end">结束</button>
</div>
</div>
<script>
const arrName = ['励志轩', '荷叶饭', '来上课', '好耶', '产业化', '雷阵雨', '蚊子咬']
const start = document.querySelector('.start')
const qs = document.querySelector('.qs')
let n = 0
let random = 0
start.addEventListener('click', function () {
n = setInterval(function () {
random = parseInt((Math.random() * arrName.length))
// console.log(arrName[random]);
qs.innerHTML = arrName[random]
}, 35)
if (arrName.length === 1) {
start.disabled = true
end.disabled = true
}
})
const end = document.querySelector('.end')
end.addEventListener('click', function () {
clearInterval(n)
arrName.splice(random, 1)
console.log(arrName)
})
</script>
</body>
</html>
生成随机数的变量在定时器结束后有一个销毁,所以可以一直承载不同的数据
事件类型
焦点:光标被激活的位置
光标位置:小竖线/横线的位置
现在大部分的光标都为一个小竖线,规则的闪动;
而在DOS下有些光标则是短短的小横线,同样规则的闪动;
现用的windows光标是一个图像,可以是动态的也可以是静态的,在不同情况下样子也不同。
鼠标位置:移动鼠标停下时的所在坐标位置
通过监听某个事件执行某些函数
举个例子:
键盘事件:例如按下回车发送评论
监听文本框的内容,每改变一次输入内容,执行一次函数
可以获取文本框输入的内容
console.log(input.valu