javascript - 动态注释掉 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>
解决方案
您应该保留用户正在使用的模式(亮或暗)
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">');
}
}
推荐阅读
- sap-gui - SAP TCODE 提取工具请求
- python - 通过正则表达式打印特定单词
- javascript - 是否可以使用 for 循环使用按钮显示值?
- swift - @Environment(\.presentationMode) var 模式:绑定
混淆其他观点 - button - 如何在不沿 z 轴移动按钮的情况下将平面几何按钮放在一排立方体的顶部?
- cmake - ROS - find_package - 其他本地包中的味精
- python - 如何在 django-restframework 中的 URL 中传递值
- firebase - 如何有条件地将数据添加到 Firebase Firestore?
- vim - 是否可以在 vim 中禁用鼠标视觉模式?
- c++ - 在 Omnet++ 中将非 cObject 数据(自定义类)添加到数据包中