设置网站夜间模式

超简单的给网站添加夜间模式

代码语言:javascript
复制
let brightness = 0;//显示遮罩
let div;
function cover(brightness) {
  if (typeof (div) === 'undefined') {
    div = document.createElement('div');
    div.setAttribute('style', 'position:fixed;top:0;left:0;outline:50000px solid;z-index:99999;');
    document.body.appendChild(div);
  } else {
    div.style.display = '';
  }
  div.style.outlineColor = 'rgba(0,0,0,' + brightness + ')';
}
window.addEventListener('keydown', function (e) {//事件监听
  if (e.altKey && e.keyCode === 90) {//Alt+Z 关灯
    cover(brightness = 0.3);
  }
  if (e.altKey && e.keyCode === 88) {//Alt+X 开灯
    cover(brightness = 0);
  }
  if (e.altKey && e.keyCode === 38) {//Alt+↑ 亮度调高
    if (brightness - 0.05 > 0.05) {
      cover(brightness -= 0.05);
    }
  }
  if (e.altKey && e.keyCode === 40) {//Alt+↓ 亮度调低
    if (brightness + 0.05 < 0.95) {
      cover(brightness += 0.05);
    }
  }
}, false);