猿问

在切换时更改标签文本

我目前在我的浏览器中有一个工作暗模式开关,当我打开时,我的网站变成黑色,当我关闭时,我的网站变成白色。

但问题是,我想更改切换按钮旁边的“暗模式”标签,以便在切换关闭时文本更改为“亮模式”,在切换打开时更改为“暗模式”。

我该怎么做?

这是当前外观的图片(注意:“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;

}


慕的地6264312
浏览 157回答 3
3回答

Smart猫小萌

在您的情况下,将 ID 添加到要更改的文本中:<label class="custom-control-label" id="modelLabel" for="darkSwitch">Dark Mode</label>并按如下方式更新您的 resetTheme() 函数:function resetTheme() {&nbsp; var modelLabel = document.getElementById("modelLabel");&nbsp; if(darkSwitch.checked){&nbsp; &nbsp; (document.body.setAttribute("data-theme", "dark"),&nbsp; &nbsp; &nbsp; localStorage.setItem("darkSwitch", "dark"));&nbsp; &nbsp; modelLabel.innerHTML = "Light Mode";&nbsp; }&nbsp; else{&nbsp; &nbsp; (document.body.removeAttribute("data-theme"),&nbsp; &nbsp; &nbsp; localStorage.removeItem("darkSwitch"));&nbsp; &nbsp; &nbsp; &nbsp; modelLabel.innerHTML = "Dark Mode";&nbsp; }&nbsp;&nbsp;}希望能帮助到你 :)

慕哥9229398

您可以从标签中删除文本并使用 css:before在其中添加内容。[for="darkSwitch"]:before{&nbsp; content:'Dark Mode'}[data-theme="dark"] [for="darkSwitch"]:before{&nbsp; content:'Light Mode'}演示在https://jsfiddle.net/ju2n3svy/

至尊宝的传说

为标签提供一个 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 Modelabel.innertHTML="Light Mode"; //If Dark Mode
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答