使用javascript為網頁增加夜間模式

來源:互聯網
上載者:User

 如何給Web頁面增加夜間模式功能? 其實所謂的夜間模式就是在頁面上增加一個透明的遮罩層,但是遮罩層會擋住頁面元素, 解決方案是 添加DIV,給DIV的outline屬性一個很大的outline-width值,用outline的邊框作為遮罩,這樣既能正常點擊頁面元素,又能達到夜間模式的效果

HTML+CSS:  代碼如下:<div class="cover"></div> 代碼如下:<style>.cover{    position:fixed;    top: 0px;    left: 0px;    outline:5000px solid rgba(0, 0, 0, 0.3);    z-index: 99999;}</style>  接著用JavaScript寫個夜間模式plus:  代碼如下:<script>var brightness;//顯示遮罩function cover(brightness) {    if (typeof(div) == 'undefined') {        div = document.createElement('div');        div.setAttribute('style', 'position:fixed;top:0;left:0;outline:5000px 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);</script>  還可以寫成GreaseMonkey指令碼,作為瀏覽器延伸給任意頁面增加夜間模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.