我想有一个基本的黑暗模式链接到一个按键。我是JavaScript的初学者,我不能让它开始工作。我想要的是,你按下一个键,黑暗模式在js上用cookie打开,而我再次按相同的键关闭黑暗模式并删除Cookie。有人能帮我吗?
这是我的守则:
var elem = document.getElementById("folie");
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
let zahl = 1;
if (key.keyCode == "70") {
if (zahl == 1) {
zahl++
dark()
Cookies.set("Darkmode", "An");
}
if (zahl == 2) {
zahl--
Cookies.remove("Darkmode")
}
}
}
var DarkCookie = Cookies.get("Darkmode");
if (DarkCookie == 'An') {
dark();
}
function dark() {
var element = document.body;
element.classList.toggle("dark-mode");
}编辑:
好的,我知道了:
let CookieDarkMode = false;
function toggleDarkMode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode === 70) { //"F" has been pressed
CookieDarkMode = !CookieDarkMode;
console.log("Cookie Dark mode: " + CookieDarkMode);
toggleDarkMode();
if (CookieDarkMode) {
Cookies.set("Darkmode", "An");
}else {
Cookies.remove("Darkmode");
}
}
};
var DarkCookie = Cookies.get("Darkmode")
if (DarkCookie == 'An') {
CookieDarkMode = true;
toggleDarkMode();
}发布于 2020-02-05 14:30:25
你不需要储存一个号码。您只需使用布尔值获取前面的cookie值即可。
let CookieDarkMode = false;
function toggleDarkMode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode === 70) { //"F" has been pressed
CookieDarkMode = !CookieDarkMode;
console.log("Cookie Dark mode: " + CookieDarkMode);
toggleDarkMode();
}
};body {
background-color: ghostwhite;
}
.dark-mode {
background-color: black;
color: white;
}<body>
<p>Lorem Ipsum</p>
</body>
发布于 2020-02-05 14:27:17
您的问题在于您的checkKeyPress函数,您总是检查zahl值,但它总是以1的形式开始。
为了演示的目的,您基本上是这样做的:
function sum(){
let zahl = 1;
zahl++
console.log(zahl)
}
// you will never see a 3, because you are creating `zhl`
// in each call with a value of 1
sum();
sum();
sum();
sum();
因此,每次检查zahl变量时,它都是1,并且总是进入打开darkmode的if。
您的代码的解决方案是将zahl变量移出函数范围之外:
let zahl = 1; // outside the function scope
var elem = document.getElementById("folie");
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode == "70") {
if (zahl == 1) {
zahl++
dark()
Cookies.set("Darkmode", "An");
}else if (zahl == 2) {
zahl--
Cookies.remove("Darkmode")
dark(); //you should call dark here as well to toggle to the other mode.
}
}
}
var DarkCookie = Cookies.get("Darkmode");
if (DarkCookie == 'An') {
dark();
}
function dark() {
var element = document.body;
element.classList.toggle("dark-mode");
}注意:它看起来并不是最好的实现,如果您使用布尔值来表示模式的状态,或者如果您想要多个类型,则可以使用名称作为每种模式的键。
https://stackoverflow.com/questions/60077760
复制相似问题