javascript - 使用深色或浅色模式
问题描述
将此类内容合并到我的网站的最佳方法是什么?我试过使用插件,但我无法让它工作。不一定要花哨。
有没有人有它或过去使用过他们可以推荐的一个?否则,有没有办法使用 JavaScript 对其进行编码?
解决方案
也许这应该可以帮助您启动。
<html class="theme-light">
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.theme-light {
--color-primary: #0060df;
--color-secondary: #fbfbfe;
--color-accent: #fd6f53;
--font-color: #000000;
}
.theme-dark {
--color-primary: #17ed90;
--color-secondary: #243133;
--color-accent: #12cdea;
--font-color: #ffffff;
}
.container {
display: flex;
width: 100%;
height: 100%;
background: var(--color-secondary);
flex-direction: column;
justify-content: center;
align-items: center;
}
.container h1 {
color: var(--font-color);
}
.container button {
color: var(--font-color);
background: var(--color-primary);
padding: 10px 20px;
border: 0;
border-radius: 5px;
}
</style>
<script>
// Set a Theme
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
document.documentElement.className = themeName;
}
// Toggle From light and dark theme and Vice-Versa
function toggleTheme() {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-light');
} else {
setTheme('theme-dark');
}
}
// Onload Theme
(function() {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-dark');
} else {
setTheme('theme-light');
}
})();
</script>
<body>
<div class="container">
<h1>Theme Switcher</h1>
<button id="switch" onclick="toggleTheme()">Switch Theme</button>
</div>
</body>
</html>
推荐阅读
- python - 通过 MPI [MPI4py] 发送复数时的 MPI_ERR_TRUNCATE
- r - 类数组 | 如何转换为数据框
- kotlin - 请解释物业代表
- java - 在用java编写的破砖游戏中,如果它同时击中两块砖,我应该如何防止速度反转两次?
- html - addEventListener 到 HTMLDivElement 数组
- python - 如何在 Holoviews 中显示围绕 GridSpace/GridMatrix 的内轴?
- php - PHP中的重复函数
- ruby-on-rails - 将链接放入 Rails 中的验证消息中
- vba - 设置标题列的名称 - 预期 14 个列名称
- python - PyTest 测试什么时候应该是类的一部分,什么时候应该是独立的方法?