我正在尝试设置黑暗模式。这种逻辑不太有效。
我已经多次重新排列了变量。我不太清楚。
var isDarkMode = false;
var darkModeToggle = false;
function toggleDarkMode(){
if (isDarkMode === false && darkModeToggle === false){
isDarkMode = true;
setDarkMode();
}
if (isDarkMode === true && darkModeToggle === true){
isDarkMode = false;
setDarkMode();
darkModeToggle = false;
}
darkModeToggle = true;
}
function setDarkMode(){
if (isDarkMode === true){
//Change to dark
}
if (isDarkMode === false){
//Change to light
}
}
我已经完成了其余的功能。我想我缺少一些简单的东西,我只是不知道它是什么。
答案 0 :(得分:1)
您不需要两个变量。只需保留一个变量即可跟踪当前模式。看下面的工作示例:
var isDarkMode = false;
function toggleDarkMode(){
var $el = document.getElementById("test");
if (!isDarkMode){
//Change to dark
$el.style.background = "black";
$el.style.color = "white";
} else {
//Change to light
$el.style.background = "white";
$el.style.color = "black";
}
isDarkMode = !isDarkMode;
}
#test {
background: white;
color: black;
}
<p id ="test"> Test Paragraph </p>
<button onclick = "toggleDarkMode()"> Toggle Dark Mode </button>
答案 1 :(得分:1)
您使事情变得有些复杂。我不知道使用darkModeToggle
变量的原因,因此我将其排除在解决方案之外。
toggleDarkMode()
就像
isDarkMode = !isDarkMode;
setDarkMode();
var isDarkMode = false;
function toggleDarkMode() {
isDarkMode = !isDarkMode;
setDarkMode();
}
function setDarkMode() {
if (isDarkMode) {
console.log("Change to dark");
} else {
console.log("Change to light");
}
}
toggleDarkMode();
toggleDarkMode();
toggleDarkMode();
toggleDarkMode();
答案 2 :(得分:1)
<main>
的{{1}}元素。.dark
。将此三元控制语句放入切换函数中:
let mode = false
“如果main具有类/* pseudo-code:*/ mode = condition........... if.true...else..false
/* real code..:*/ mode = main.matches('.dark') ? true : false;
,则.dark
是mode
,否则它的true
”
在演示中的任意位置单击以切换黑暗模式。
false
let mode = false;
const main = document.querySelector('main');
main.onclick = toggleMode;
function toggleMode(e) {
if (e.target.matches('main')) {
e.target.classList.toggle('dark');
mode = main.matches('.dark') ? true : false;
console.log(mode);
}
return false;
}
* {
margin: 0;
padding: 0;
}
:root {
font: 700 small-caps 3vw/1.2 Taholma;
}
main {
height: 100vh;
width: 100vw;
background: #dad;
}
h1 {
text-align: center;
pointer-events: none;
}
.dark {
color: #fc0;
background: #000;
}
h1::before {
content: 'Default ';
}
.dark h1::before {
content: 'Dark ';
}