网站添加暗黑模式html+js

有些时候我们喜欢大半夜不睡觉刷抖音刷微博,突发奇想为什么我们不能让网站在夜间的时候自动打开夜间模式,让网页背景变暗,让图片变暗,这样那些夜猫观看我们的博客时候就不会那么刺眼啦,哈哈。话不多说,上教程!

首先第一步,在您的页面footer文件加入以下js代码。

  1. < script type = "text/javascript" >
  2. function switchNightMode() {
  3. var night = document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || "0";
  4. if (night == "0") {
  5. document.body.classList.add("night");
  6. document.cookie = "night=1;path=/";
  7. console.log("夜间模式开启")
  8. } else {
  9. document.body.classList.remove("night");
  10. document.cookie = "night=0;path=/";
  11. console.log("夜间模式关闭")
  12. }
  13. } (function() {
  14. if (document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") === "") {
  15. if (new Date().getHours() > 21 || new Date().getHours() < 6) {
  16. document.body.classList.add("night");
  17. document.cookie = "night=1;path=/";
  18. console.log("夜间模式开启")
  19. } else {
  20. document.body.classList.remove("night");
  21. document.cookie = "night=0;path=/";
  22. console.log("夜间模式关闭")
  23. }
  24. } else {
  25. var night = document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || "0";
  26. if (night == "0") {
  27. document.body.classList.remove("night")
  28. } else {
  29. if (night == "1") {
  30. document.body.classList.add("night")
  31. }
  32. }
  33. }
  34. })();
  35. </script>

加好后在您的页面body处加入php判断,这样当检测到cookie相关字段时直接输出body的class为night,已防止页面闪烁。

  1. <body class="<?php echo($_COOKIE['night'] == '1' ? 'night' : ''); ?>">

最后再将网站中所有需要变暗的地方调整其css,已达到变暗效果,具体css调整示例可看下方

  1. body.night 需要调整的区块{
  2. background-color: #000000;
  3. color: #aaa;
  4. }
  5. body.night img {
  6. filter: brightness(30%);
  7. }

这样当晚上9点到白天6点之间,网站打开时就自动会变成暗黑模式。当然,你也可以加一个按钮,来手动控制打开关闭暗黑模式。如下代码

  1. <a href="javascript:switchNightMode()" target="_self">Dark</a>

至此教程就结束了,需要强调的是,该方法需要修改的css非常的多,需要大家细心的调整及适配,不太建议过于复杂的网站添加此功能,不然css写到你哭,哈哈!

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/95
1 条评论
4.8k

发表评论

仅有一条评论

  1. 佛系软件     Win 10 /    Chrome
    2020-11-09 14:47

    可以根据操作系统变换颜色吗

!