[英]How to revert changes to css made by javascript
So I have a button that toggles a simple dark theme for my web app. 所以我有一个按钮,可以为我的网络应用切换一个简单的黑暗主题。
<button class="btn btn-primary" onclick="dark_mode()">Dark Mode ON</button>
Once the user clicks it will activate this function in javascript. 一旦用户点击它将在javascript中激活此功能。
function dark_mode() {
document.body.style.background = "#2C2F33";}
This will only change the background. 这只会改变背景。 I am wondering if the user clicks the button a second time it will revert the changes made by the function.
我想知道用户是否第二次点击按钮它将恢复该功能所做的更改。 (ie toggle on/off) Thanks for the time and help in advance!
(即打开/关闭)感谢您提前的时间和帮助!
Just check and change the style using a ternary operator: 只需使用三元运算符检查并更改样式:
function dark_mode() {
document.body.style.background = document.body.style.background == "#2C2F33" ? "#FFFFFF" : "#2C2F33";
}
You can make it by toggling CSS class, it is more flexible solution 你可以通过切换CSS类来实现它,它是更灵活的解决方案
function dark_mode() { document.body.classList.toggle('dark-mode') }
.dark-mode { background: #2C2F33 }
<button class="btn btn-primary" onclick="dark_mode()">Dark Mode ON</button>
If the user clicks again, the function is simply called again. 如果用户再次单击,则只需再次调用该函数。 So, after the first click there are no more changes.
因此,在第一次点击后,没有更多的变化。
A better way would be to assign your dark mode styles to a class, say "btn--dark-mode" and then use js to toggle that class: 更好的方法是将黑暗模式样式分配给一个类,比如“btn - dark-mode”,然后使用js来切换该类:
function dark_mode() { document.querySelector('#dark-mode-toggle').classList.toggle('dark-mode'); // ie9+ only }
.btn--dark-mode { background-color: #2C2F33; }
<button id="dark-mode-toggle" class="btn btn-primary" onclick="dark_mode()">Dark Mode ON</button>
This will apply the class or take it off depending on whether it is already there. 这将适用于课程或取消它取决于它是否已经存在。
You can use data
tags to track current theme : 您可以使用
data
标记来跟踪当前主题:
<button class="btn btn-primary" onclick="dark_mode(this);" data-dark-theme="on" >Dark Mode ON</button>
JS : JS:
function dark_mode(ctrl) {
var darkTheme = ctrl.getAttribute("data-dark-theme");
if(darkTheme== "on"){
ctrl.setAttribute("data-dark-theme", "off");
document.body.style.background = "#2C2F33";
ctrl.innerHTML = "Dark Mode OFF";
}
else {
ctrl.setAttribute("data-dark-theme", "on");
document.body.style.background = "#FFFFFF";
ctrl.innerHTML = "Dark Mode ON";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.