我希望能够单击切换 UI 元素(复选框),并让它显示/隐藏一个或另一个 div。
如果只是为了简单起见而使用 CSS 来实现这一点,那就太棒了;但我知道是否需要 javascript/jQuery。
当前的 CSS(如下)只是一些样式;我无法更改我的基本 DIV HTML 结构。
input[type="checkbox"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
-webkit-tap-highlight-color: transparent;
cursor: pointer; }
input[type="checkbox"]:focus {
outline: 0; }
.toggle {
height: 32px;
width: 52px;
border-radius: 16px;
display: inline-block;
position: relative;
margin: 0;
border: 2px solid #474755;
background: linear-gradient(180deg, #2D2F39 0%, #1F2027 100%);
transition: all .2s ease; }
.toggle:after {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 24px;
height: 24px;
border-radius: 50%;
background: white;
box-shadow: 0 1px 2px rgba(44, 44, 44, 0.2);
transition: all 0.2s cubic-bezier(0.5, 0.1, 0.75, 1.35); }
.toggle:checked {
border-color: #654FEC; }
.toggle:checked:after {
transform: translatex(20px); }
<div id="a">...</div>
<div id="b">...</div>
<div id="c">
<div>
<div>
<input type="checkbox" class="toggle" checked>
</div>
</div>
</div>
<div id="d">...</div>
<div id="content-one">Content one</div>
<div id="content-two">Content two</div>
<div id="e">...</div>
</div>
编辑:
我还想分享 ChatGPT (Bing Chat) 提供的一个更简单的版本(什么也没做,哈哈):
#content-two {
display: none;
}
.toggle:checked ~ #content-two {
display: normal;
}
.toggle:checked ~ #content-one {
display: none;
}
<div id="a">...</div>
<div id="b">...</div>
<div id="c">
<div>
<div>
<input type="checkbox" class="toggle" checked>
</div>
</div>
</div>
<div id="d">...</div>
<div id="content-one">Content one</div>
<div id="content-two">Content two</div>
<div id="e">...</div>
使用
:has()
和 :not(:has())
就可以了
input[type="checkbox"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
-webkit-tap-highlight-color: transparent;
cursor: pointer;
}
input[type="checkbox"]:focus {
outline: 0;
}
.toggle {
height: 32px;
width: 52px;
border-radius: 16px;
display: inline-block;
position: relative;
margin: 0;
border: 2px solid #474755;
background: linear-gradient(180deg, #2D2F39 0%, #1F2027 100%);
transition: all .2s ease;
}
.toggle:after {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 24px;
height: 24px;
border-radius: 50%;
background: white;
box-shadow: 0 1px 2px rgba(44, 44, 44, 0.2);
transition: all 0.2s cubic-bezier(0.5, 0.1, 0.75, 1.35);
}
.toggle:checked {
border-color: #654FEC;
}
.toggle:checked:after {
transform: translatex(20px);
}
#c:has(.toggle:checked) ~ [id=content-one] {
display: none;
}
#c:not(:has(.toggle:checked)) ~ [id=content-two] {
display: none;
}
<div id="a">...</div>
<div id="b">...</div>
<div id="c">
<div>
<div>
<input type="checkbox" class="toggle" checked>
</div>
</div>
</div>
<div id="d">...</div>
<div id="content-one">Content one</div>
<div id="content-two">Content two</div>
<div id="e">...</div>