一招解决Modal多个弹窗遮罩层颜色加深问题

131 阅读1分钟

问题背景: 在Modal触发多个弹窗时,遮罩层颜色加深,导致用户无法清晰地看到弹窗遮罩下面的内容。

这里用的是一个简易封装的组件,如果没有使用这种方式在每次打开弹窗前调用 dealMaskStyle 检查并处理样式就好

//获取页面所有的弹窗只留一个弹窗的遮罩,其他的都改成透明色
export function dealMaskStyle() {
  const maskList = document.getElementsByClassName('ant-modal-mask') as HTMLCollectionOf<HTMLElement>;
    let visibleMasks = Array.from(maskList).filter((item) => item.style.display !== 'none');
    if (visibleMasks.length > 1) {
        for (let i = 1; i < visibleMasks.length; i++) {
            visibleMasks[i].classList.add('nb666');
        }
    }
}

export function useDialog({ title } = {}) {
    const visible = ref(false);

    function openDialog() {
        visible.value = true;
        dealMaskStyle();
    }

    function closeDialog() {
        visible.value = false;
    }

    return {
        visible,
        title,
        openDialog,
        closeDialog,
    };
}

/*destroy-on-close 关闭时销毁 Modal 里的子元素*/
<template>
    <a-modal
        :class="['dialog', themeType]"
        v-model:visible="props.openVis"
        :title="props.title"
        :width="props.width"
        :maskClosable="true"
        @cancel="handleCancel"
        destroy-on-close
    >
        <slot name="container"></slot>
        <template #footer></template>
    </a-modal>
</template>

<script setup lang="ts">
    import { useTheme } from '/@/hooks/theme/useTheme.ts';
    import { nextTick } from 'vue';

    const emit = defineEmits(['close']);
    const props = defineProps({
        width: {
            type: String,
        },
        openVis: {
            type: Boolean,
        },
        title: {
            type: String,
        },
    });
    const { themeType } = useTheme();

    function handleCancel() {
        emit('close');
    }
</script>
.ant-modal-mask {
	background-color: #00000073 !important;
}

/* 为其他所有的 .ant-modal-mask 设置透明背景 */
.ant-modal-mask.nb666 {
	background-color: transparent !important;
}