css属性:图片使用filter属性使得position: fixed失效的情况
众所周知,position: fixed属性可以让我们的元素相对于当前视口的大小,让元素定位到指定页面的指定位置,也是我们经常使用的一个css属性
position: fixed; //参考视口定位
left: 50%;
top: 20px;
transform: translate(-50%);
但是今天在使用过程中,突然发现,这个position: fixed属性居然出现了问题:我的元素居然不是根据视口的宽度显示了????
1、问题复现
让我们复现一下这个问题:
img{filter: saturate(200%); //图片饱和度width: 180px;
}.model{width: 200px;height: 150px;background-color: skyblue;border-radius: 10px;padding: 5px;box-shadow: 0 0 5px;text-align: center;position: fixed; //参考视口定位left: 50%;top: 20px;transform: translate(-50%);
}
这是为什么呢??后来发现,当我把fillter属性注释掉之后,居然又正常了。。。。好奇怪的问题。
2、问题原因
后来百度了一大推,发现原来filter会影响元素的父元素,导致position的参考对象变了,不再是body元素了,变成了filter的父元素,这当然不行了!!!
3、问题解决
在vue3中提供了一个teleport标签,可以直接解决这个问题,只要将我们需要添加position: fixed;的元素包裹起来,并指定他的参考元素,就行了。
<template><button @click="isShow=true">展示弹窗</button><teleport to='body' ><div v-if="isShow" class="model"><h2>我是弹窗的标题</h2><p>我是弹窗的内容</p><button @click="isShow=false">关闭弹窗</button></div></teleport>
</template><script lang="ts" setup>
import { ref } from "vue";
let isShow = ref(false)
</script><style lang="scss" scoped>
.model{width: 200px;height: 150px;background-color: skyblue;border-radius: 10px;padding: 5px;box-shadow: 0 0 5px;text-align: center;position: fixed; //参考视口定位left: 50%;top: 20px;transform: translate(-50%);
}
</style>