簡體   English   中英

使用 javascript 切換按鈕上的文本

[英]Toggling a text on button using javascript

我正在嘗試創建一個暗模式切換按鈕,我需要以下文本屬性:-

  1. 當主題是淺色時,應該會出現Turn on dark mode
  2. 如果主題為深色,則應Turn off dark mode

僅此而已,目前,我正在使用以下代碼在暗模式和亮模式之間切換,但問題在於按鈕。 我嘗試了不同的代碼,但文本以錯誤的方式交換。 https://codepen.io/vkdatta27/pen/oNxrxad

<script>const btn = document.querySelector(".btn-toggle");

const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
  document.body.classList.add("dark"); 
}

btn.addEventListener("click", function () {
  document.body.classList.toggle("dark");

  let theme = "light";
  if (document.body.classList.contains("dark")) {
    theme = "dark"; 
 
  }

  localStorage.setItem("theme", theme);
});
</script>
<style>
.btn-toggle {
border-radius: 20px;
float: center;
outline: none;
border: 25px;
padding: 10px;
width: fit;
font-size: 15px;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
text-align:center;
box-shadow:  5px 5px 10px #5c5c5f, 
             -5px -5px 10px #ffffff;
background-color: #101010;
color: #e6e7ee;
}
body.dark .btn-toggle {
box-shadow:  5px 5px 10px #121212, 
             -5px -5px 10px #4a4a4a;
color: #101010 !important;
background-color: #e6e7ee;
}
body.dark .btn-toggle a {
color: #101010 !important;
}
body {background-color: #e6e7ee}
body.dark {background-color: #101010; color:#ffffff}
</style>
<button class="btn-toggle" id="btn-id"></button>

在您的情況下,您實際上並不需要 Javascript 來完成任務:

邏輯:

  • .dark關閉時,顯示文本 1 - 這是默認設置
  • .dark打開時,顯示文本 2 - 當 CSS 類.dark處於活動狀態時

CSS:

/* ADDED */
.btn-toggle::before { content: 'dark mode' }       /* default text of the button */
.dark .btn-toggle::before { content: 'light mode' }/* overwrite the default text*/
/*********/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM