当前位置:   article > 正文

网站夜间模式的实现思路与详细教程分享_网站夜晚

网站夜晚

网站夜间模式是怎样实现的?

整体思路

夜间模式开关按钮:用来手动切换夜间模式的,会存储cookie。

自动夜间模式:当cookie为空时,浏览器时间大于22点小于6点时会自动进入夜间模式,并存储cookie。

后端配合:php判断是否有cookie,有的话直接输出夜间css,避免切换页面时网页闪烁。

具体操作

引入黑夜 css

有title熟悉rel属性值同时包含alternate stylesheet的<link>作为备选样式CSS文件加载,默认不渲染。

切换夜间模式的 js 函数

  1. function switchNightMode() {
  2. var night = document.cookie.replace(/(?:(?:^|.;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '0';
  3. if(night == '0'){
  4. document.querySelector('link[title="dark"]').disabled = true;
  5. document.querySelector('link[title="dark"]').disabled = false;
  6. document.cookie = "night=1;path=/"
  7. console.log('夜间模式开启');
  8. }else{
  9. document.querySelector('link[title="dark"]').disabled = true;
  10. document.cookie = "night=0;path=/"
  11. console.log('夜间模式关闭');
  12. }
  13. }

指定时间进入夜间模式

  1. (function(){
  2. if(document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/,"$1") === ''){
  3. if(new Date().getHours() > 22 || new Date().getHours() < 6){
  4. document.querySelector('link[title="dark"]').disabled = true;
  5. document.querySelector('link[title="dark"]').disabled = false;
  6. document.cookie = "night=1;path=/"
  7. console.log('夜间模式开启');
  8. }else{
  9. document.cookie = "night=0;path=/"
  10. console.log('夜间模式关闭');
  11. }
  12. }else{
  13. var night = document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") ||'0';
  14. if(night == '0'){
  15. document.querySelector('link[title="dark"]').disabled = true;
  16. console.log('夜间模式关闭');
  17. }else if(night == '1'){
  18. document.querySelector('link[title="dark"]').disabled = true;
  19. document.querySelector('link[title="dark"]').disabled = false;
  20. console.log('夜间模式开启');
  21. }
  22. }
  23. })();

php 后端判断 cookie 进行加载 css

<link href="dark.css" rel="<?php if($_COOKIE['night'] != '1'){echo 'alternate ';} ?>stylesheet" type="text/css" title="dark"

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/736113
推荐阅读
相关标签
  

闽ICP备14008679号