追悼日网站自动变为黑白(解决filter导致的absolute和fixed定位问题)

  • 当 filter 不为 none 的时候,如果该元素或者其子元素具有 absolute 或 fixed 属性,那么它会为其创建一个新的包含块/容器,会造成该 absolute 或 fixed 元素的定位发生变化(就是改变了 absolute 或 fixed 元素的定位 父 元素,变成新创建的元素)。
  • 例如:当在 body 标签中使用了 filter 属性后(body { filter: grayscale(100%); ), filter 就会生成一个新的包含块,其位置大小和 body 一样,然后 fixed 元素就会根据这个包含块进行定位,导致定位出现问题。
  • 如果 filter 设置在根元素上( html { filter: grayscale(100%); ),它是不会为 absolute 或 fixed 子元素创建新的包含块的,因此我们可以通过将filter设置在根元素(html)上来避免定位问题。
// 在项目入口文件App.vue中进行以下设置
created () {
    this.getMournDate()
},
methods: {
    getMournDate () {
      // 调用接口获取后台设置的追悼日期范围(起始日~截止日)
      this.mournDate = {
        start: 1669824000000, // 2022-12-01
        end: 1670601600000 // 2022-12-10
      }
      this.checkMourn(this.mournDate)
    },
    checkMourn (mournDate) {
      var now = new Date().getTime()
      if (mournDate.start <= now && now <= mournDate.end) {
        // 追悼日只有设置在html元素上才不会影响fixed和absolute定位
        document.documentElement.style.filter = 'grayscale(100%)'
        setTimeout(() => { // 自动取消黑白
          document.documentElement.style.filter = 'none'
        }, mournDate.end - now)
      } else {
        document.documentElement.style.filter = 'none'
        if (now < mournDate.start) { // 自动变为黑白
          setTimeout(() => {
            document.documentElement.style.filter = 'grayscale(100%)'
          }, mournDate.start - now)
        }
      }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值