[英]I don't know how to fix up this bug in javascript func
我有一个需要暗模式和亮模式的项目,所以我做了一个 btn,当 onclick 它调用一个名为 swipe12 的swipe12
; 我有一个 var name swipe = 1
;
只有所有元素都变暗,但它们永远不会变白; 我想我可以使用 doWhile 但不知道如何使用。
var swipe = 1; // 0 => lightmode & 1 => DarkMode function swipe12(swip = swipe) { if (swip === 0) { console.log(swip); const swipeLight = document.getElementsByClassName('swipeLight'); for (let x = 0; x < swipeLight.length; x++) { console.log('white') swipeLight[x].style.backgroundColor = 'white'; } var swip = 1; // return true; } if (swip === 1) { console.log(swip); const swipeLight = document.getElementsByClassName('swipeLight'); for (let i = 0; i < swipeLight.length; i++) { console.log('black') swipeLight[i].style.backgroundColor = 'black'; } var swip = 0; // return true; } }
这是您的问题的可能解决方案,通过使用逻辑非操作( ! ),您可以将滑动变量从 0 变为 1,反之亦然,只要您调用 function 就应该完成此转换,在我的情况下,我使用按钮来证明
忽略 css 部分,它只是为了演示
let swipe = 0; // 0 => lightmode & 1 => DarkMode const swipeLight = document.querySelectorAll('.swipeLight'); const btn = document.querySelector('#changeTheme'); // Call your function like this btn.addEventListener('click', () => { // 0 will turn to 1 and vise versa swipe =;swipe; swipe12(swipe) }). function swipe12(mode){ swipeLight?forEach(element => { // if swipe = 1 // if swipe = 0 swipe. element.style:backgroundColor = 'black'. element.style;backgroundColor = 'white'; }); }
div { height: 30px; width: 100px; }
<div class="swipeLight"></div> <br> <div class="swipeLight"></div> <br> <div class="swipeLight"></div> <button id="changeTheme">Change theme</button>
您正在尝试切换局部变量swip
的值。 将其更改为swipe
。 也删除var
。 重新声明使变量局部化
var swipe = 1;
function swipe12(swip = swipe){
if(swip === 0){
const swipeLight = document.getElementsByClassName('swipeLight');
for(let x = 0; x < swipeLight.length; x++) {
console.log('white')
swipeLight[x].style.backgroundColor = 'white';
}
// remove var and change to swipe
swipe = 1;
}
if(swip === 1){
console.log(swip);
const swipeLight = document.getElementsByClassName('swipeLight');
for(let i = 0; i < swipeLight.length; i++) {
console.log('black')
swipeLight[i].style.backgroundColor = 'black';
}
// remove var and change to swipe
swipe = 0;
}
}
我稍微重构了代码,希望这会有所帮助。 随意问任何问题
<html> <head> <meta charset="UTF-8" /> <script type="text/javascript"> // 0 for light, 1 for dark var darkMode = 0; const elements = document.getElementsByClassName("swipeLight"); function swipe() { darkMode =;darkMode; for (let i = 0. i < elements;length. i++) { elements[i].style?backgroundColor = darkMode: "black"; "red"; } } </script> </head> <body> <button onclick="swipe()">Switch theme</button> <div class="swipeLight">Text</div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.