javascript - 使用 JavaScript 更改 HTML 本地存储图标和暗模式
问题描述
我用我自己的深色主题制作了一个深色模式按钮。主题由本地存储保存。此外,当我单击按钮时,它的图标会发生变化(月亮到太阳)。但是,如果我重新加载页面,该站点仍处于黑暗模式,但按钮图标又是月亮。所以这里有一个链接,如果你不明白我在说什么,它会告诉你问题。(https://postimg.cc/yg6Q3vq0)还有我的代码:
//This is the darkmode script.
function darkmode() {
const wasDarkmode = localStorage.getItem('darkmode') === 'true';
localStorage.setItem('darkmode', !wasDarkmode);
const element = document.body;
element.classList.toggle('dark-mode', !wasDarkmode);
}
function onload() {
document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');
}
//End
//And this is the code which change the button's icon
$('button').on('click', fav);
function fav(e) {
$(this).find('.fa').toggleClass('fa-moon-o fa-sun-o');
}
//So I would like to combine the 2 codes. I mean to add the icon code to Local Storage.
.card {
color: yellow;
background-color: blue;
}
.dark-mode .car {
color: blue;
background-color: yellow;
}
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<a style="padding: 0 !important;"><button class="darkmode" onclick="darkmode()"><i class="fa fa-moon-o"></i></button></a>
<div class="card">
<h1>Title</h1>
<p>Text<//p>
<h2>Another text..</h2>
</div>
</body>
</html>
解决方案
浏览器只是按照编写的方式呈现 HTML。您的 HTML 表示要 render <i class="fa fa-moon-o"></i>
,这就是浏览器显示的内容。换句话说,默认情况下它总是显示月亮图标。
您需要对页面加载执行某种检查,以查看是否应更改图标。
像这样的东西可能会起作用:
// when the document is ready
$(document).ready(function () {
// check if dark mode is enabled
if (localStorage.getItem('darkmode') === 'true') {
// if it is, change the moon icon to a sun icon
('.fa').toggleClass('fa-moon-o fa-sun-o');
}
});
推荐阅读
- mysql - 安全销毁(粉碎)MySQL 数据库
- docker - K8s 不在 Persistent Volume 上挂载文件
- java - 如何在 mapreduce 中创建自定义映射器类
- java - Dockerized Spring Boot 应用程序中的 FileSystemNotFoundException
- c# - 使用 .NET Core 中的 NEST 对 ElasticSearch 中的嵌套集合执行查询
- javascript - 无法使用 v-if 获取元素的 id
- apache-spark - 在 Spark 结构化流中处理来自传入运动流的空批次
- go - 如何获取系统解析器的 DNS 服务器列表
- reactjs - 如何将自定义属性传递给 TypeScript + StyledCompoments?
- angular - 将 nth-child 绑定到数组,Angular