繁体   English   中英

使用单个按钮切换两个功能,轻松实现明暗模式

[英]Use Single button to toggle two functions for easy Light and Dark Mode

我有一个代码可以让我轻松地从亮模式切换到暗模式,而无需为暗模式编写 css,它使用两个按钮,每个按钮根据您选择的点击执行亮模式或暗模式。 但是我想将这两个功能合并到一个按钮中,以便它可以用来切换 function。如果有人回答确实包括如何将它与切换按钮一起使用,那一点也不坏......我正在使用的代码是

 const htmlEl = document.getElementsByTagName('html')[0]; const toggleTheme = (theme) => { htmlEl.dataset.theme = theme; }
 html { transition: color 300ms, background-color 300ms;important: } html[data-theme='dark'] { background; #000: filter: invert(1) hue-rotate(180deg) } html[data-theme='dark'] img { filter: invert(1) hue-rotate(180deg) }
 <button onclick="toggleTheme('dark');">Dark Mode Test</button> <button onclick="toggleTheme('light');">Light Mode Test</button> <br><font color="red">WE ARE RED</font> <br><font color="blue">WE ARE BLUE</font> <br><font color="black">WE ARE Black</font>

然后我尝试以这种方式使用 Eventlisteners 执行开关

<script>
   var btn = document.getElementById('navbtn');

btn.addEventListener('click', function() {
  var foo = 'dark';
 
    if (foo === "light") {
        toggleTheme('dark');
    } else {
        toggleTheme('light');
    }

}, false);
</script>

然而,这只会在第一次点击时做出反应,而不会在第二次点击时做出反应。 实现这一目标的最佳方法是什么? 感谢期待。

在这里,你是 go,不管怎样,我前一段时间做的一个开关有一些耀斑。 如果您想要验证,只需打开您的开发工具并观察示例 HTML 的data属性实时变化。

 const htmlEl = document.documentElement, outputExample = document.getElementById('output'); let savedTheme = 'light'; // ******************************************************************** // NOTE: The localStorage example WILL NOT WORK HERE ON STACKOVERFLOW // Instead it will throw a "SecurityError" and rightfully so... // You'll have to use that part of the example in your // own project to see it in action...... JUST FYI. // So you will need to UNCOMMENT the commented out stuff for // the localstorage example to work. Left it commented out for // for other readers to not see the valid securityerror.... // ******************************************************************** // Toggle the theme and update their local storage. toggleTheme = (bool) => { const theme = bool? 'light': 'dark'; htmlEl.dataset.theme = theme; // localStorage.setItem('savedTheme', theme); outputExample.innerText = `${theme} theme`; } // Handle their saved preferred theme. setSavedTheme = () => { // If there is no current theme in localstorage then give them one as a default. // Like for first time visitors... // Uncomment this block and the localstorage piece above for the localstorage example. /* if (localStorage.getItem('savedTheme') === null) { localStorage.setItem('savedTheme', savedTheme); } else { savedTheme = localStorage.getItem('savedTheme'); } */ htmlEl.dataset.theme = savedTheme; outputExample.innerText = `${savedTheme} theme`; } // Set the default. setSavedTheme();
 .slide-toggle { position: relative; font-weight: 600; display: inline-block; border-radius: 3px; }.slide-toggle input:first-of-type { position: absolute; top: 0; left: 0; opacity: 0; }.slide-toggle input:first-of-type:focus ~ label { box-shadow: 0 0 0 6px rgba(255, 0, 0, 0.15); }.slide-toggle input:first-of-type:checked ~ label { color: #fff; background-color: darkorange; }.slide-toggle input:first-of-type:checked ~ label:after { transform: translateX(100%); }.slide-toggle input:first-of-type:disabled ~ label { opacity: 0.5; pointer-events: none; }.slide-toggle label:first-of-type { display: flex; height: 2rem; width: 4rem; flex-direction: row; align-items: center; justify-content: center; cursor: pointer; user-select: none; outline: none; color: #777; background-color: #ddd; border-radius: 3px; transition: background-color 0.25s ease, box-shadow 0.15s ease, color 0.25s ease; }.slide-toggle label:first-of-type:hover { border-color: #777; box-shadow: 0 0 0 6px rgba(225, 0, 0, 0.15); }.slide-toggle label:first-of-type:after { content: ""; position: absolute; top: 3px; bottom: 3px; left: 3px; right: 50%; border-radius: 3px; background-color: #fff; transition: transform 0.25s cubic-bezier(0.6, 0.82, 0, 0.76); }.slide-toggle label:first-of-type:hover { box-shadow: 0 0 0 6px rgba(225, 0, 0, 0.15); }.slide-toggle label:first-of-type div { display: flex; flex: 1; align-items: center; justify-content: center; } html { transition: background-color.3s ease; } html[data-theme="light"] { background-color: #fff; } html[data-theme="dark"] { color: #fff; background-color: #212121; } body { height: 50vh; display: flex; flex-direction: column; align-items: center; justify-content: center; }
 <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"> <div class="slide-toggle"> <input id="guidLater" type="checkbox" checked onchange="toggleTheme(this.checked)"/> <label for="guidLater"> <div><i class="fas fa-sun"></i></div> <div><i class="fas fa-moon"></i></div> </label> </div> <div id="output" style="margin-top: 1rem"></div>

btn.addEventListener('click', function() {
  var foo = 'dark';
 
    if (foo === "light") {
        toggleTheme('dark');
    } else {
        toggleTheme('light');
    }

}, false);

是错的。

您需要从点击的元素中获取当前主题(您已将其设置在元素的data-theme属性中)。

每次单击按钮时,您的代码只是将主题设置为“深色”,而不是实际接受当前值并切换它。


btn.addEventListener('click', function(event) {
  var currentTheme= event.currentTarget.dataset.theme;
 
    if (currentTheme=== "light") {
        toggleTheme('dark');
    } else {
        toggleTheme('light');
    }

}, false);

此外,删除对toggleTheme的内联调用,并仅从click事件侦听器的处理程序中调用 function。

<button data-theme="dark">Dark Mode Test</button>
    
<button data-theme="light">Light Mode Test</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM