想要实现的效果:
HTML代码:
<el-button @click="state.dialog.visible = true">打开对话框</el-button>
<el-dialog v-model="state.dialog.visible" :title="state.dialog.title" class="dialog">
<el-button @click="state.drawer.visible = true">打开抽屉</el-button>
<el-drawer v-model="state.drawer.visible" :title="state.drawer.title" modal-class="test123" size="30%">
<template #footer>
<el-button>取消</el-button>
<el-button type="primary">确定</el-button>
</template>
</el-drawer>
<template #footer>
<el-button>取消</el-button>
<el-button type="primary">确定</el-button>
</template>
</el-dialog>
JS代码:
<script setup>
const state = reactive({
dialog: {
title: '对话框',
visible: false
},
drawer: {
title: '抽屉',
visible: false
}
})
</script>
结果:
很显然,结果与我们预期不符,皮裤套棉裤,必定有缘故。为什么?怎么办?
原因:因为el-dialog与el-drawer的父级遮罩都使用了css定位属性position: fixed;
Fixed
定位是相对于浏览器视口来定位的,也就是说,元素的位置不会随着页面滚动而改变,始终会固定在视口的某个位置。元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。脱离文档流不占空间。
解决办法:将抽屉的遮罩定位到对话框上,即让对话框作为抽屉定位的参照物
在el-drawer
标签上添加modal-class
属性自定义遮罩的css样式,详情见ElementPlus官方文档,设置css定位样式为position: absolute;
Absolute
定位是相对于 static(position默认值)定位以外的第一个父元素进行定位,如果不存在已定位的父元素,则相对于body元素。元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。