---
title: "javascript夜间模式"
author: "weistar"
date: "2013-12-06T16:11:58Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: true
lastmod: "2013-12-06T16:51:17Z"
id: 1986280
url: "https://weistar.iteye.com/blog/1986280"
---

javascript夜间模式

代码：

```
function sunMoon() {
    var styleElem = null,
    doc = document,
    ie = doc.all,
    fontColor = 50,
    sel = 'body,body *';
    var styleElem = createCSS(sel, setStyle(fontColor), styleElem);
    showTip(doc);
    if (ie) {
        doc.attachEvent('onkeydown', onKeyDown);
    } else {
        doc.addEventListener('keydown', onKeyDown);
    };
    function onKeyDown(evt) {
        if (! (evt.keyCode === 87 || evt.keyCode === 81)) return;
        var evt = ie ? window.event: evt;
        if (evt.keyCode === 87) {
            fontColor = (fontColor >= 100) ? 100 : fontColor + 10
        } else if (evt.keyCode === 81) {
            fontColor = (fontColor <= 10) ? 10 : fontColor - 10
        };
        styleElem = createCSS(sel, setStyle(fontColor), styleElem);
    };
    function setStyle(fontColor) {
        var colorArr = [fontColor, fontColor, fontColor];
        return 'background-color:#000 !important;color:RGB(' + colorArr.join('%,') + '%) !important;'
    };
    function createCSS(sel, decl, styleElem) {
        var doc = document,
        h = doc.getElementsByTagName('head')[0],
        styleElem = styleElem;
        if (!styleElem) {
            s = doc.createElement('style');
            s.setAttribute('type', 'text/css');
            styleElem = ie ? doc.styleSheets[doc.styleSheets.length - 1] : h.appendChild(s);
        };
        if (ie) {
            styleElem.addRule(sel, decl);
        } else {
            styleElem.innerHTML = '';
            styleElem.appendChild(doc.createTextNode(sel + ' {' + decl + '}'));
        };
        return styleElem;
    };
    function showTip() {
        var tipElem = doc.createElement('div'),
        body = doc.getElementsByTagName('body')[0];
        tipElem.innerHTML = '===夜间模式开启，q&w可增减字体亮度===';
        tipElem.style.cssText = 'background-color:#3FA9FB !important;color:#fff !important;font-size:14px;height:20px;line-height:20px;position:fixed;left:0;top:0;text-align:center;width:100%;z-index:99999;';
        body.appendChild(tipElem);
        setTimeout(function() {
            body.removeChild(tipElem);
        },
        3000);
    }
}
```

 函数会在页面增加如下内容：

```
<style type="text/css">
body,body * {background-color:#000 !important;color:RGB(50%,50%,50%) !important;}
</style>
```

 功能：

支持chrome，firefox，ie

q键：减少字体亮度

w键：增加字体亮度

要恢复刷新页面即可

 

 使用1：

&lt;a href="javascript:(sunMoon)();"&gt;夜间模式&lt;/a&gt;

 使用2：

在浏览器标签栏上添加标签，内容为：'javascript:(sunMoon)();'，将括号中内容替换为上面的函数即可。