实现效果:

效果说明:
初始状态时,广告窗默认显示,点击关闭按钮后,广告窗隐藏,1s后广告窗再次出现,第四次点击关闭按钮的时候,广告窗彻底关闭。
由于代码较少,故全部写在index.html中,index.html代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>弹窗</title>
</head>
<style>
.box {
position: fixed;
top: 10px;
left: 10px;
width: 200px;
height: 100px;
border: 1px solid #e8e8e8;
background: rgba(200, 200, 200, .8);
}
.box > span.close {
position: absolute;
top: 0;
right: 0;
width: 20px;
height: 20px;
text-align: center;
color: #ffffff;
user-select: none;
background: rgba(200, 200, 200, 0.8);
}
.box > span.title {
display: block;
margin-top: 20px;
color: red;
}
</style>
<body>
<div class="box">
<span class="close"> X </span>
<span class="title">点击关闭按钮后,弹窗先消失再出现,第四次关闭后,弹窗彻底清除。</span>
</div>
<script type="text/javascript">
let box = document.getElementsByClassName('box')[0];
let close = document.getElementsByClassName('close')[0];
let num = 0;
close.onclick = function () {
closeTC()
};
function closeTC() {
num++;
console.log(num);
if (num <= 3) {
box.style.display = 'none';
setTimeout(function () {
box.style.display = 'block';
}, 1000)
} else {
box.parentNode.removeChild(box);
}
}
</script>
</body>
</html>
JS代码详解:
1、getElementsByClassName为什么后面要加[0]?
getElementsByClassName为类名选择器,结果集为数组,需要指定抓取的对象为数组中的某一个,故需要在后面使用:[下标]指定具体抓取的对象。
2、怎么控制隐藏之后再显示?
在点击关闭按钮后,让整个广告窗的display属性设置为“none”(隐藏),再使用定时器,在1s后,将display属性设置为"block"(显示)。
3、怎么控制第四次点击的时候广告窗直接隐藏,不再出现?
定义变量num记录点击的次数,在num小于等于3的时候,执行2所述情况,当num大于3时,使用广告窗的父节点将本节点删除,故不再出现。
2270

被折叠的 条评论
为什么被折叠?



