<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>事件监听</title>
<style>
.box {
background-color: pink;
font-size: 50px;
line-height: 200px;
font-weight: 700;
}
.box1 {
position: absolute;
right: 20px;
top: 10px;
width: 20px;
height: 20px;
background-color: skyblue;
text-align: center;
line-height: 20px;
font-size: 16px;
cursor: pointer;//鼠标变小手
}
</style>
</head>
<body>
<!-- 事件:在编程时系统内发生的事件
事件监听:事件被触发会作出响应
-->
<!-- <button>xx</button> -->
<div class="box">
是的,我是广告位,目前在招租
<div class="box1">
x
</div>
</div>
<script>
//语法:元素对象.addEventlistener('事件类型',要执行的函数),函数不会立即执行,等事件触发才会执行
// 事件监听三要素:
// 事件源:哪个dom元素被事件触发了,要获取dom元素;
// 事件类型:用什么方式触发,例如鼠标点击;
// 事件调用的函数:要做什么事
// 需求:点击按钮弹出一个对话框
// 事件源
// const btn = document.querySelector('button')
// btn.addEventListener('click', function () {
// alert('zaozaozao')
// })//click鼠标点击事件
// 大盒子关闭小盒子也会被关闭
const box1 = document.querySelector('.box1')
const box = document.querySelector('.box')
// 事件侦听
box1.addEventListener('click', function () {
box.style.display = 'none'
})
</script>
</body>
</html>
案例结果