CSS 的 filter 属性提供了一种简单的方法来实现这一点。
1 2 3 |
html { filter: grayscale(100%); } |
或者,如果你想要对整个页面应用这个效果,你也可以使用:
1 2 3 |
body * { filter: grayscale(100%) !important; } |
注意:使用 !important 是为了确保该样式能覆盖其他可能影响颜色的样式。
另一种方法是使用 SVG 滤镜。这通常是更复杂的做法,但它提供了更多的控制能力。
首先,创建一个 SVG 文件(或直接在 HTML 文件中嵌入 SVG):
1 2 3 4 5 |
<svg xmlns="http://www.w3.org/2000/svg"> <filter id="grayscale"> <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0" /> </filter> </svg> |
然后,在 CSS 中引用这个滤镜:
1 2 3 |
html { filter: url(#grayscale); } |
或者
1 2 3 |
body * { filter: url(#grayscale) !important; } |
如果你想要能够动态地开启或关闭这个效果,你可以使用 JavaScript 来添加或删除一个样式类:
1 2 3 4 |
function toggleGrayscale() { const element = document.documentElement; element.classList.toggle('grayscale'); } |
然后在 CSS 中定义这个样式类:
1 2 3 |
.grayscale { filter: grayscale(100%); } |
这样,你就可以通过调用 toggleGrayscale() 函数来动态地开启或关闭灰度效果。
以上就是几种实现网站变灰的方法,你可以根据自己的需求来选择最适合你的方案。