首页 > 解决方案 > 动态注释掉 CSS 样式表?

问题描述

我用本地存储为网站构建了相当繁重的明暗模式。从一个切换到另一个是无缝的,两者看起来都很棒。然而,我在导航暗模式时遇到了闪烁的问题。

两个样式表都以这个顺序在我的 header.php 中


    <link id="light" rel="stylesheet" type="text/css" title="day" href="https://example.com/public/css/main.css">
    <link id="dark" rel="stylesheet" type="text/css" title="night" href="https://example.com/public/css/night.css">

localstorage 开关在同一个文件中使用 javascript 向下处理。

在尝试了一百万件事之后,结果是当我注释掉上面提到的第一个样式表时,闪烁消失了,浏览是无缝的。

所以我的问题是:如何使用将添加到 localstorage 部分的一些 javascript 命令注释掉样式表的第一行?还是有另一种方法可以动态地注释掉该样式表?

这是我需要在其中的本地存储功能:

<script>
document.getElementById("light").href = localStorage.getItem('light');
document.getElementById("dark").href = localStorage.getItem('dark');

function dayoff() {
document.getElementById("light").href = 'https://example.com/public/css/night.css';
    localStorage.setItem( 'light', 'https://example.com/public/css/night.css' );
document.getElementById("light").href = 'https://example.com/public/css/night.css';
    localStorage.setItem( 'dark', 'https://example.com/public/css/night.css' );
document.getElementById("logo").src = 'https://example.com/public/img/toplogo-night.png';
    location.reload();
}
</script>

标签: javascriptcss

解决方案


您应该保留用户正在使用的模式(亮或暗)

localStorage.setItem('mode', 'light or dark');

然后您应该根据用户使用的模式添加样式表。

你的功能

function dayoff() {
   // toggle function 
   if(localStorage.getItem("mode") === null || localStorage.getItem("mode") == "light"){
       localStorage.setItem("mode", "dark");
   }
   else{
       localStorage.setItem("mode", "light");
   }
   location.reload();
}
if(localStorage.getItem("mode") === null){
   // first time visitors
    $('head').append('<link id="light" rel="stylesheet" type="text/css" href="https://example.com/public/css/main.css">');
}
else{
   // returning users
   if(localStorage.getItem('mode') == "light"){
      $('head').append('<link id="light" rel="stylesheet" type="text/css" href="https://example.com/public/css/main.css">');
   }
   else{
      $('head').append('<link id="dark" rel="stylesheet" type="text/css" href="https://example.com/public/css/dark.css">');
   }
}

推荐阅读