事件监听就是让计算机监视一个事件是否发生。事件是用户或浏览器自身执行的某种动作,如click,load和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>
</head>
<style>
.box{
width: 100px;
height: 100px;
background-color: purple;
}
</style>
<body>
<div class="box"></div>
</body>
<script>
//事件监听 元素对象.addEventListtener('事件类型',要执行的函数)
const box = document.querySelector('.box')
//鼠标点击
box.addEventListener('click',function(){
console.log('鼠标点击')
})
//鼠标经过
box.addEventListener('mouseenter',function(){
console.log('鼠标经过')
})
//鼠标离开
box.addEventListener('mouseleave',function(){
console.log('鼠标离开')
})
//获得焦点
box.addEventListener('focus',function(){
console.log('焦点获得')
})
//失去焦点
box.addEventListener('blur',function(){
console.log('焦点失去')
})
//键盘按下
box.addEventListener('keydown',function(){
console.log('按下键盘')
})
//键盘抬起
box.addEventListener('keyup',function(){
console.log('键盘抬起')
})
//表单输入
box.addEventListener('input',function(){
console.log('用户输入')
})
</script>
</html>