有一个简单的需求,就是在网页加载的时候,直接弹出一个活动的弹框,很多网站都用这个功能做一些活动提示。
但是这个功能要是用组件库来实现的话,就有点麻烦,因为需要屏蔽组件库的很多功能和样式,比如弹框头部标题,底部按钮,背景色等等。其实使用原生js很容易就能实现这样的功能。
先上图给大家看看效果,如果有类似的需求可以参考一下。
以下是基于vue2的实现,其中有一些样式可能需要调整。
弹框组件Modal
<template> <div class="modal"> <div class="modal-content"> <div class="modal-header"> <button @click="close" style="font-size: 32px;color: white">X</button> </div> <div class="modal-body"> <slot></slot> </div> </div> <div class="modal-overlay"></div> </div></template>
<script>58 collapsed lines
export default { name: 'Modal', props: { title: { type: String, default: 'Modal Title' } }, methods: { close() { this.$emit('close'); } }}</script>
<style>.modal { position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 9999;}
.modal-overlay { position: fixed; top: 0; left: 0; bottom: 0; right: 0; background: rgba(0, 0, 0, 0.5); z-index: 9999;}
.modal-content { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: transparent; padding: 20px; border-radius: 5px; z-index: 100000;}.modal-header{ display: flex; align-items: center; justify-content: end;}.modal-header button { border: none; background: transparent; font-size: 20px; cursor: pointer;}</style>使用方式
<template> ... <button @click="showModal">开启Modal</button> <modal v-if="show" @close="closeModal" > <img src="./xxxxxx.png" alt=""> </modal> ...</template><script>import Modal from './Modal.vue';
export default { data() { return { show: false,11 collapsed lines
} }, methods: { showModal() { this.show = true; }, closeModal() { this.show = false; } },}问题
如果遇到了蒙层没有完全覆盖页面,可能需要调整一下蒙层的z-index属性。