js添加事件监听
- 事件源(btn)
- 事件类型(click)
- 事件处理(function)
addEventListener
<!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{
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<button>点击</button>
</body>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click',function(){
alert('hi');
})
</script>
</html>
实例:关闭显示框
<!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: 500px;
height: 500px;
background-color: antiquewhite;
}
.box1{
width: 20px;
height: 20px;
background-color: red;
}
</style>
<body>
<div class="box">
<div class="box1">X</div>
</div>
</body>
<script>
// 获取事件源
const box1 = document.querySelector('.box1')
// 关闭box
const box = document.querySelector('.box')
box1.addEventListener('click',function(){
box.style.display ='none'
})
</script>
</html>