[英]Toggling a text on button using javascript
I'm trying to create a dark mode toggle button and I require following text properties :-我正在尝试创建一个暗模式切换按钮,我需要以下文本属性:-
Turn on dark mode
should appear when theme is a light oneTurn on dark mode
Turn off dark mode
should appear if theme is dark one.Turn off dark mode
。 Nothing more, Currently, I'm using follwing code to toggle between dark and light mode but the issue comes with button.仅此而已,目前,我正在使用以下代码在暗模式和亮模式之间切换,但问题在于按钮。 I tried different codes but the text gets swapped in a wrong manner.
我尝试了不同的代码,但文本以错误的方式交换。 https://codepen.io/vkdatta27/pen/oNxrxad .
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>
In your case you don't really need Javascript to get things done:在您的情况下,您实际上并不需要 Javascript 来完成任务:
Logic:逻辑:
.dark
is off, show text 1 - this is the default.dark
关闭时,显示文本 1 - 这是默认设置.dark
is on, show text 2 - when CSS class .dark
is active.dark
打开时,显示文本 2 - 当 CSS 类.dark
处于活动状态时CSS: 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.