vue弹窗关闭(点击阴影部分)

前言:
大多时候我们都会有写弹窗的需求、除了点击按钮关闭之外,随着用户友好性的要求增加、点击弹窗外部的阴影部分关闭弹窗也成了交互更加友好的体验。

一、问题注意

写代码之前这里需要注意两个点
1.关闭事件内不要传参数!不要传参数!不要传参数!
2. 弹窗需要设置高度

二、代码实现

1、文本内容部分(主要分成两层、透明区域一层、内容一层)

<div id="common_alert" v-if="show_common_alert" @click="closeMsg">
    <div class="common_alert_box" id="common_alert_box">
      <span @click="close_alert"></span>
      <div v-if="show_common_alert">
        <h3>vue弹窗显示</h3>
        <img :src="imgUrl" />
        <button @click="close_alert">知道了</button>
      </div>
    </div>
  </div>

2、弹窗样式我就不说明了直接上代码吧

#common_alert {
  position: fixed;
  width: 100%;
  height: 100vh;
  background: rgba(142, 140, 140, 0.51);
  .common_alert_box {
    position: relative;
    width: 240px;
    height: 411px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    h3 {
      color: rgba(16, 16, 16, 1);
      font-size: 14px;
      text-align: center;
      font-family: PingFangSC-regular;
      padding-top: 38px;
    }
    img {
      width: 200px;
      height: 222px;
      margin: 15px auto 33px;
    }
    span {
      width: 15px;
      height: 15px;
      background: url("./static/close.png");
      background-size: 15px;
      position: absolute;
      top: 15px;
      right: 15px;
    }
    .close_alert {
      position: absolute;
      top: 10px;
      right: 15px;
    }
  }
}

效果如下图
在这里插入图片描述

3、具体的vue实现如下所示

 data() {
    return {
      show_common_alert: true
    };
  },
 methods: {
 //关闭按钮
    close_alert() {
      this.show_common_alert = false;
    },
    // 点击弹窗之外的地方关闭弹窗
    closeMsg(el) {
    //获取弹窗节点
      var con = document.getElementById("common_alert_box");
      if (con) {
      //判断如果不是当前节点就隐藏弹窗
        if (!con.contains(el.target)) {
          this.show_common_alert = false;
        }
      }
    }
  },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章