网站置灰,问题总结

198 阅读1分钟

最近哀悼日,在网上也看了几篇相关的文章,把实践的问题给汇总下。

主要代码

html{ 
    filter: grayscale(100%); 
    /* 考虑到兼容性 */
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
}

坑点

小程序上,如果页面代码有「绝对和固定定位的后代」,加上filter:grayscale(100%)之后,导致相关样式的属性失效。

解决

  1. 找到对应的元素,且这个元素没有「绝对和固定定位的后代」,加上filter;(工作量大,不是优解)
  2. backdrop-filter
html {
  width: 100%;
  height: 100%;
  position: relative;
}
html::before {
  content: "";
  **position: fixed;**
  backdrop-filter: grayscale(100%);
  pointer-events: none;  /*遮罩层不影响事件交互*/
  inset: 0;
  z-index: 10;
} 

进阶

置灰网页首屏,非首屏部分不需要置灰

page {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #F3F4F6;
}
page::before {
  content: "";
  **position: absolute;**
  backdrop-filter: grayscale(100%);
  pointer-events: none;
  inset: 0;
  z-index: 10;
}

知识点

  1. fixed 和 absolute
    通过css看出首屏和非首屏的区别是html::before里设置的fixed 和 absolute.
  • fixed定位元素的位置相对于浏览器窗口是固定位置,不会随着窗口滚动移动.
  • absolute定位相对于最近已定位的父元素,如果没有已定位的父元素,则相对于html.
  1. filter 和 backdrop-filter
  • filter 作用于当前元素和它的后代元素
  • backdrop-filter 作用于当前元素背后的所有元素

image.png 3. 对于需要更好兼容的,使用混合模式mix-blend-mode: huemix-blend-mode: saturationmix-blend-mode: color 也都是非常好的方式

参考文章

# 除了 filter 还有什么置灰网站的方式?