gpt4 book ai didi

javascript - 如何使用 JavaScript 一键切换两种背景颜色

转载 作者:行者123 更新时间:2023-11-30 09:25:21 25 4
gpt4 key购买 nike

我发布了一个与此类似的问题,人们提供的解决方案有效,但只有在我注释掉所有其他 CSS 代码时它才有效。出于某种原因,CSS 干扰了 JavaScript 函数的正常工作。我想在单击按钮时将背景颜色更改为黑色,但是当我再次单击它时又想将其更改回白色。

<!DOCTYPE html>
<html>
<head>
<title>Light Switch</title>
<link rel="stylesheet" href="light.css" />
</head>

<body id="body">
<div id="click">
<label id="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</div>
<script src="light.js"></script>
</body>
</html>


#switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
margin: 0 auto;
}

#switch input {
display: none;
}

.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: grey;
-webkit-transition: .4s;
transition: .4s;
border-radius: 34px;
}

.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
background-color: white;
bottom: 4px;
transition: .4s;
border-radius: 50%;
}

input:checked + .slider {
background-color: #1583ea;
}

input:checked + .slider:before {
transform: translateX(26px);
}


function start() {
var click = document.getElementById("switch");
click.addEventListener("click", toggle);
};

function toggle() {
var color = document.getElementById("body");
var backColor = color.style.backgroundColor;
color.style.backgroundColor = backColor === "black" ? "white" : "black";
};


start();

最佳答案

由于开关 div 上的事件监听器而不是 slider 本身,您的函数触发了两次。我稍微重构了你的代码。

function start() {
var toggleSwitch = document.getElementById("slider");
toggleSwitch.addEventListener("click", toggle);
};

function toggle() {
var backColor = document.body.style.backgroundColor;
document.body.style.backgroundColor = backColor === "black" ? "white" : "black";
};


start();
#switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
margin: 0 auto;
}

#switch input {
display: none;
}

.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: grey;
-webkit-transition: .4s;
transition: .4s;
border-radius: 34px;
}

.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
background-color: white;
bottom: 4px;
transition: .4s;
border-radius: 50%;
}

input:checked + .slider {
background-color: #1583ea;
}

input:checked + .slider:before {
transform: translateX(26px);
}
<!DOCTYPE html>
<html>
<head>
<title>Light Switch</title>
<link rel="stylesheet" href="light.css" />
</head>

<body>
<div>
<label id="switch">
<input type="checkbox" checked>
<span id="slider" class="slider"></span>
</label>
</div>
<script src="light.js"></script>
</body>
</html>

关于javascript - 如何使用 JavaScript 一键切换两种背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49325964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com