我目前在浏览器中有一个工作的暗模式开关,当我打开时,我的网站变成黑色,当我关闭时,我的网站变成白色。
但事情是,我想改变“黑暗模式”标签旁边的切换,这样文本更改为“光明模式”时,切换关闭,“黑暗模式”时,切换打开。
我该怎么做?
从HTML:
<div class="nav-link">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="darkSwitch" />
<label class="custom-control-label" for="darkSwitch">Dark Mode</label>
</div>
<!-- Javascript For Darkmode Switch -->
<script src="index.js"></script>
</div>
来自JavaScript的摘录:
const darkSwitch = document.getElementById("darkSwitch");
function initTheme() {
const e =
null !== localStorage.getItem("darkSwitch") &&
"dark" === localStorage.getItem("darkSwitch");
(darkSwitch.checked = e),
e
? document.body.setAttribute("data-theme", "dark")
: document.body.removeAttribute("data-theme");
}
function resetTheme() {
darkSwitch.checked
? (document.body.setAttribute("data-theme", "dark"),
localStorage.setItem("darkSwitch", "dark"))
: (document.body.removeAttribute("data-theme"),
localStorage.removeItem("darkSwitch"));
}
window.addEventListener("load", () => {
darkSwitch &&
(initTheme(),
darkSwitch.addEventListener("change", () => {
resetTheme();
}));
});
从CSS:
[data-theme="dark"] {
background-color: #111 !important;
color: #eee;
}
[data-theme="dark"] .bg-light {
background-color: #333 !important;
}
[data-theme="dark"] .bg-white {
background-color: #000 !important;
}
[data-theme="dark"] .bg-black {
background-color: #eee !important;
}
/* CSS For table */
[data-theme="dark"] .table {
background-color: #111 !important;
color: #eee;
}
将ID添加到要更改的文本中,在您的情况下:
<label class="custom-control-label" id="modelLabel" for="darkSwitch">Dark Mode</label>
并按如下方式更新resetTheme()函数:
function resetTheme() {
var modelLabel = document.getElementById("modelLabel");
if(darkSwitch.checked){
(document.body.setAttribute("data-theme", "dark"),
localStorage.setItem("darkSwitch", "dark"));
modelLabel.innerHTML = "Light Mode";
}
else{
(document.body.removeAttribute("data-theme"),
localStorage.removeItem("darkSwitch"));
modelLabel.innerHTML = "Dark Mode";
}
}
希望有帮助:)
给标签一个ID,并使用DOM更改文本。
<label class="custom-control-label" for="darkSwitch" id="darkLabel">Dark Mode</label>
var label=document.getElementById("darkLabel");
label.innertHTML="Dark Mode"; //If Light Mode
label.innertHTML="Light Mode"; //If Dark Mode
您可以从标签中删除文本,并使用css:before
在其中添加内容。
[for="darkSwitch"]:before{
content:'Dark Mode'
}
[data-theme="dark"] [for="darkSwitch"]:before{
content:'Light Mode'
}
演示:https://jsfiddle.net/ju2n3svy/