【问题标题】:Comment out CSS stylesheet dynamically?动态注释掉 CSS 样式表?
【发布时间】:2019-12-19 15:00:02
【问题描述】:

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

两个样式表都以这个顺序在我的 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">

本地存储开关在同一个文件中使用 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>

【问题讨论】:

  • 我会在服务器端这样做。默认情况下,用户有一些样式,而另一种甚至不存在于 HTML 标记中。用户选择另一种样式并从 PHP 中保留一个 cookie(数据库字段会更好)并更改 CSS。
  • 你能展示你的完整功能吗?
  • 没问题。

标签: javascript css


【解决方案1】:

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

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">');
   }
}

【讨论】:

  • 因为它是 jquery,我可以将它添加到处理本地存储的 javascript 函数中吗?让我将我用来“关灯”的功能添加到我的问题中。
  • 我假设你使用 js localstorage?那么是的
  • 但是对于初次访问者来说,需要有一个标准模式(最好是轻的)。一个或另一个应该是活动的。如果没有设置样式,网站会看起来很奇怪,不是吗?顺便感谢您的宝贵时间。
  • 查看我更新的答案,这是您要找的吗?
  • 太棒了,只是解析它。你愿意加入我的聊天室几分钟吗,这件事对我来说真的很重要。我可以告诉你整个事情的样子。
猜你喜欢
  • 2011-03-18
  • 2020-02-02
  • 2013-01-02
  • 1970-01-01
  • 2020-04-30
  • 2011-10-13
  • 2023-03-16
  • 1970-01-01
  • 2010-10-07
相关资源
最近更新 更多