有一个简单的需求,就是在网页加载的时候,直接弹出一个活动的弹框,很多网站都用这个功能做一些活动提示。 但是这个功能要是用组件库来实现的话,就有点麻烦,因为需要屏蔽组件库的很多功能和样式,比如弹框头部标题,底部按钮,背景色等等。其实使用原生js很容易就能实现这样的功能。 先上图给大家看看效果,如果有类似的需求可以参考一下。 以下是基于vue2的实现,其中有一些样式可能需要调整。 弹框组件Modal 1<template>2 <div class="modal">3 <div class="modal-content">4 <div class="modal-header">5 <button @click="close" style="font-size: 32px;color: white">X</button>6 </div>7 <div class="modal-body">8 <slot></slot>9 </div>10 </div>11 <div class="modal-overlay"></div>12 </div>13</template>14 15<script>58 collapsed lines16export default {17 name: 'Modal',18 props: {19 title: {20 type: String,21 default: 'Modal Title'22 }23 },24 methods: {25 close() {26 this.$emit('close');27 }28 }29}30</script>31 32<style>33.modal {34 position: fixed;35 top: 0;36 left: 0;37 bottom: 0;38 right: 0;39 z-index: 9999;40}41 42.modal-overlay {43 position: fixed;44 top: 0;45 left: 0;46 bottom: 0;47 right: 0;48 background: rgba(0, 0, 0, 0.5);49 z-index: 9999;50}51 52.modal-content {53 position: fixed;54 top: 50%;55 left: 50%;56 transform: translate(-50%, -50%);57 background: transparent;58 padding: 20px;59 border-radius: 5px;60 z-index: 100000;61}62.modal-header{63 display: flex;64 align-items: center;65 justify-content: end;66}67.modal-header button {68 border: none;69 background: transparent;70 font-size: 20px;71 cursor: pointer;72}73</style> 使用方式 1<template>2 ...3 <button @click="showModal">开启Modal</button>4 <modal v-if="show" @close="closeModal" >5 <img src="./xxxxxx.png" alt="">6 </modal>7 ...8</template>9<script>10import Modal from './Modal.vue';11 12export default {13 data() {14 return {15 show: false,11 collapsed lines16 }17 },18 methods: {19 showModal() {20 this.show = true;21 },22 closeModal() {23 this.show = false;24 }25 },26} 问题 如果遇到了蒙层没有完全覆盖页面,可能需要调整一下蒙层的z-index属性。