1. 利用 css 样式
html {
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
-webkit-filter: grayscale(1);
}
2. 利用 JS 代码封装成为可以自定义时间去置灰和取消置灰
(function (window) {
function GlobalGray(start, end) {
this.today = new Date();
this.start = new Date(start);
this.end = new Date(end);
}
GlobalGray.prototype.isInRange = function () {
return this.today >= this.start && this.today <= this.end
}
GlobalGray.prototype.appendStyle = function () {
var css = "html {";
css += "-webkit-filter: grayscale(100%);";
css += "-moz-filter: grayscale(100%);";
css += "-o-filter: grayscale(100%);";
css += "filter: grayscale(100%);";
css += "filter: gray;";
css += "-ms-filter: 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)';";
css += "}";
var styleElement = document.createElement('style');
styleElement.type = 'text/css';
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = css; // 兼容 IE
} else {
styleElement.appendChild(document.createTextNode(css)); // 标准写法
}
document.head.appendChild(styleElement);
}
GlobalGray.prototype.setGray = function () {
if (this.isInRange()) {
this.appendStyle();
}
};
window.GlobalGray = GlobalGray;
})(window);
在 index.html 使用
<script src="/libs/gray.js"></script>
<script> var g = new GlobalGray("2023/11/2 00:00:00", "2023/11/3 00:00:00"); g.setGray(); </script>