目录
实现在页面上添加一个小广告,同时为该小广告添加关闭按钮,用户点击关闭按钮后,小广告就会被隐藏起来。
下面是这段代码的详细解析和说明:
1. 添加小广告
程序使用一个 div 元素,并设置该元素的宽度、高度、背景颜色、字体颜色、文字大小、文本居中、行高等样式,来实现一个小广告。
.box {
width: 600px;
height: 300px;
background-color: #ff60ea;
color: aliceblue;
font-size: 60px;
text-align: center;
line-height: 300px;
margin: 0 auto;
position: relative;
/* 添加相对定位,使子元素以此为基准定位 */
}
2. 添加关闭按钮
程序在小广告的内部添加了一个 div 元素,并设置该元素的宽度、高度、边框、背景颜色、文字颜色、字体大小、位置等样式,用于表示一个关闭按钮。同时,程序还为该元素添加了一个点击事件,当用户点击该按钮时,程序将会隐藏小广告。
.box1 {
width: 20px;
height: 20px;
color: black;
border: 1px solid #000;
background-color: #fb6101;
position: absolute;
/* 添加绝对定位,才能使用 top 和 right 属性 */
top: 0;
/* 向上对齐 */
right: 0;
/* 向右对齐 */
row-gap: 20px;
cursor: pointer;
}const box1 = document.querySelector('.box1')
box1.addEventListener('click', function () {
this.parentNode.style.display = 'none'
})
3. 事件监听
程序使用了事件监听的方式,为关闭按钮添加了一个点击事件,并在事件处理函数中获取到当前按钮的父元素(也就是小广告)并更改其 display 属性,将其隐藏起来。
box1.addEventListener('click', function () {
this.parentNode.style.display = 'none'
})
4. 页面显示
通过 HTML 代码,程序将小广告和关闭按钮添加到了页面中,并且设置了相应的样式和事件。
<div class="box">
<strong>我是小广告</strong>
<div class="box1" style="font-size: 16px; line-height: 20px;"><strong>✕</strong></div>
</div>
<!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: 600px;
height: 300px;
background-color: #ff60ea;
color: aliceblue;
font-size: 60px;
text-align: center;
line-height: 300px;
margin: 0 auto;
position: relative;
/* 添加相对定位,使子元素以此为基准定位 */
}
.box1 {
width: 20px;
height: 20px;
color: black;
border: 1px solid #000;
background-color: #fb6101;
position: absolute;
/* 添加绝对定位,才能使用 top 和 right 属性 */
top: 0;
/* 向上对齐 */
right: 0;
/* 向右对齐 */
row-gap: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box">
<strong>我是小广告</strong>
<div class="box1" style="font-size: 16px; line-height: 20px;"><strong>✕</strong></div>
</div>
<script>
const box1 = document.querySelector('.box1')
box1.addEventListener('click', function () {
this.parentNode.style.display = 'none'
})
</script>
</body>
</html>