通过 css 滤镜可以非常方便的给网页完成置灰。
HTML 添加一个统一的滤镜即可
<style>
html {
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: grayscale(100%);
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
filter: gray !important;
}
</style>
如果需要保留特殊元素不被置灰,那就使用选择器:
<style>
.header, main, #footer {
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: grayscale(100%);
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
filter: gray !important;
}
</style>
其它的几种置灰方式:
使用 SVG 滤镜
<div>
// ...
</div>
<svg xmlns="https://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>
<style>
html {
filter: url(#grayscale);
}
</style>
使用 backdrop-filter 实现首屏置灰遮罩
html {
position: relative;
width: 100%;
height: 100%;
overflow: scroll;
}
html::before {
content: "";
position: absolute;
inset: 0;
backdrop-filter: grayscale(95%);
z-index: 10;
pointer-events: none;
}
借助混合模式实现网站置灰
html {
position: relative;
width: 100%;
height: 100%;
overflow: scroll;
background: #fff;
}
html::before {
content: "";
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 1);
mix-blend-mode: color;
pointer-events: none;
z-index: 10;
}
但是,IE 对以上方式无效
借助插件:grayscale.js
/*
* -- grayscale.js --
* Copyright (C) James Padolsey (http://james.padolsey.com)
*
*/
<script type="text/javascript">
window.onload = function () {
grayscale($('header,main,footer'));
}
</script>
注意,这里又是为了兼容性,最好使用 jquery,用选择器的时候能免去不少麻烦。
cd…