繁体   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