[英]Change label text on toggle
我目前在我的瀏覽器中有一個有效的暗模式開關,當我打開時,我的網站變成黑色,當我關閉時,我的網站變成白色。
但問題是,我想更改切換按鈕旁邊的“暗模式”label,以便在切換關閉時文本更改為“亮模式”,當切換打開時文本更改為“暗模式”。
我該怎么做?
這是當前外觀的圖片(注意:“Dark”這個詞根本不會隨着開關而改變)
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 如下:
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";
}
}
希望能幫助到你:)
提供 label 的 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
您可以從 label 中刪除文本並使用 css :before
將內容添加到那里。
[for="darkSwitch"]:before{
content:'Dark Mode'
}
[data-theme="dark"] [for="darkSwitch"]:before{
content:'Light Mode'
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.