我想用javascript给我的网站添加暗模式。从技术上讲,它可以工作,但不是我想要的方式。它只将主体颜色设置为黑色。但挑战是将颜色设置为"< div >“标记。老实说,我不太了解JavaScript,所以我不知道该怎么做。下面是我的代码:
document.body.style.backgroundColor = sessionStorage.getItem('bg');
document.body.style.color = sessionStorage.getItem('cc');
document.div.style.backgroundColor = sessionStorage.getItem('cardbg');
document.div.style.color = sessionStorage.getItem('cardcc');
function darker() {
if ( sessionStorage.getItem('bg') === 'rgb(241, 241, 241)') {
sessionStorage.setItem('bg', 'rgb(6, 23, 37)');
sessionStorage.setItem('cc', '#fff');
sessionStorage.setItem('cardbg', 'rgb(5, 15, 36)');
sessionStorage.setItem('cardcc', '#fff');
}
else if (sessionStorage.getItem('bg') == null || undefined) {
sessionStorage.setItem('bg', 'rgb(6, 23, 37)');
sessionStorage.setItem('cc', '#000');
sessionStorage.setItem('cardbg', 'rgb(5, 15, 36)');
sessionStorage.setItem('cardcc', '#fff');
}
else if( sessionStorage.getItem('bg') === 'rgb(6, 23, 37)') {
sessionStorage.setItem('bg', 'rgb(241, 241, 241)');
sessionStorage.setItem('cc', '#000');
sessionStorage.setItem('cardbg', 'rgb(5, 15, 36)');
sessionStorage.setItem('cardcc', '#fff');
}
document.body.style.backgroundColor = sessionStorage.getItem('bg');
document.body.style.color = sessionStorage.getItem('cc');
document.div.style.backgroundColor = sessionStorage.getItem('cardbg');
document.div.style.color = sessionStorage.getItem('cardcc');
}
<html>
<head>
<style>
body {
background-color: #f1f1f1;
color: #000;
}
.card {
background-color: red;
color: black;
}
</style>
</head>
<body>
<div class="card">
<h5>Title</h5>
<p>Some text...</p>
<p>Another text..</p>
</div>
</body>
<script src="assets/js/darker.js"></script>
</html>
发布于 2020-08-28 09:21:55
您可以将主题存储在对象中,并在运行时使用document.documentElement.style.setProperty()
进行切换
示例:
const dark = {
'background-color': '#FFFFFF'
}
const light = {
'background-color': '#000000'
}
在你的CSS中(注意:只使用body > div
)
--background-color: #000000 // this is the default
body > div {
background-color: var(--background-color);
}
最后,如果你需要切换主题,你可以这样做:
function setTheme(a_oTheme) {
Object.keys(a_oTheme).forEach(k =>
document.documentElement.style.setProperty(`--${k}`, a_oTheme[k])
);
}
https://stackoverflow.com/questions/63630804
复制相似问题