我正在学习classLists.toggle,但由于某些原因,我似乎无法真正应用该元素 切换样式,我真的很难找出我要去哪里。 我正在使用没有当前样式的ID,因此我可以在单击时打开或关闭类,但是在没有应用的情况下无法弄清楚,那里得到了被切换的样式,但是不是它的样式很奇怪 谁能解释为什么呢?
const clicked = () => {
document.getElementById("box").classList.toggle("toggle");
document.getElementById("text").classList.toggle("change");
}
body {
background-color: #42b883;
}
#text {
position: absolute;
font-size: 70px;
right: 750px;
}
#box {
height: 100px;
width: 100px;
background-color: blue;
cursor: pointer;
}
.toggle #box {
background-color: black;
}
<div id="box" onClick="clicked()"></div>
<h2 id="text">Test</h2>
答案 0 :(得分:1)
因为您的CSS规则是错误的。
.toggle #box {
应该是
#box.toggle {
您的代码正在寻找
<div class="toggle">
<div id="box"></div>
</div>