关于弹窗广告—定时器、遮罩层

时间:2022-07-23
本文章向大家介绍关于弹窗广告—定时器、遮罩层,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天在家里办公,大学同学发了个消息,说在外面谈客户,客户的网站出了问题,需要帮忙处理下。

与大学同学沟通过后,客户要求进入网站首页的用户会有一个弹框,要求用户观看某个广告,若用户点击取消按钮模态框消失,几秒后模态框再次出现。若想要模态框永远消失,需要用户点击观看广告

分析需求

分析一下这个需求,再次出现应该想到js计时器,js计时器分setInterval()和setTimeout,很显然用户的需求不是有规律的循环,所以这里会用到setTimeout,计时器会有一个数字类型的返回值,在使用结束之后记得清除。涉及到模态框、遮罩层,则会有水平垂直居中的问题。

效果图

点击前

点击后

上代码

js部分

const modelWrap = document.querySelector('.modelWrap')

const replay = (stop, t = 1000) => {
    modelWrap.style.display = 'none'
    if (stop) return false
    const num = setTimeout(() => {
        modelWrap.style.display = 'flex'
        clearTimeout(num);
    }, t)
}

const modelWrapEvent = modelWrap.addEventListener('click', (e) => {
    switch (e.target.className) {
        case "close":
            replay();
            break;
        case "watchAd":
            replay(true);
            break;
        default:
            console.log('Sorry, we are out of');;
    }
})

html部分

<div>我是页面我是页面</div>
<div class="modelWrap">
    <div class="content fadeIn">
        小广告小广告
        <button class="watchAd">观看广告</button>
        <buttton type="button" class="close">关闭</buttton>
    </div>
</div>

css部分

html,
body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

.modelWrap {
    width: 100%;
    height: 100%;
    background: rgb(150, 148, 148, .2);
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 0;
}

.modelWrap .content {
    width: 200px;
    height: 200px;
    background: #4282D3;
    position: relative;
}

.modelWrap .close {
    background: #7D71D8;
    position: absolute;
    top: 0;
    right: 0;
}

.watchAd {
    position: absolute;
    bottom: 30px;
}

最后我们再给这个弹框加上一个淡入的效果

.fadeIn {
  -webkit-animation-name: fadeIn;
  -webkit-animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-name: fadeIn;
  animation-duration: 1s;
  animation-fill-mode: both;
}
@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}
@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}