问题描述
我想使用javascript将暗模式添加到我的网站。它在技术上有效,但不是我想要的那样。它仅将主体颜色设置为黑色。但是挑战是将颜色设置为“
”标签。老实说,我并不真正了解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',37)');
sessionStorage.setItem('cc','#000');
sessionStorage.setItem('cardbg',36)');
sessionStorage.setItem('cardcc','#fff');
}
else if( sessionStorage.getItem('bg') === 'rgb(6,37)') {
sessionStorage.setItem('bg','rgb(241,241)');
sessionStorage.setItem('cc','#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>
1 个答案:
答案 0 :(得分:0)
您可以将主题存储在对象中,并在运行时使用document.documentElement.style.setProperty()
示例:
const dark = {
'background-color': '#FFFFFF'
}
const light = {
'background-color': '#000000'
}
在CSS中(注意:仅样式div的使用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])
);
}
解决方法
您可以将主题存储在对象中,并在运行时使用document.documentElement.style.setProperty()
示例:
const dark = {
'background-color': '#FFFFFF'
}
const light = {
'background-color': '#000000'
}
在CSS中(注意:仅样式div的使用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])
);
}