我正在使用以下代码为多个div生成下拉字段,但是就其本身而言,每个生成的切换按钮只会打开第一个div的切换内容。
这是我当前正在使用的:
xpath
.toggle {
display: none;
}
.option {
position: relative;
margin-bottom: 1em;
}
.bio-title,
.bio-content {
backface-visibility: hidden;
transform: translateZ(0);
transition: all 0.2s;
}
.bio-title {
background: #fff;
padding: 1em;
display: block;
color: #7A7572;
font-weight: bold;
}
.bio-title:after,
.bio-title:before {
content: "";
position: absolute;
right: 1.25em;
top: 1.25em;
width: 2px;
height: 0.75em;
background-color: #7A7572;
transition: all 0.2s;
}
.bio-title:after {
transform: rotate(90deg);
}
.bio-content {
max-height: 0;
overflow: hidden;
background-color: #fff;
}
.bio-content p {
margin: 0;
padding: 0.5em 1em 1em;
font-size: 0.9em;
line-height: 1.5;
}
.toggle:checked+.bio-title,
.toggle:checked+.bio-title+.bio-content {
box-shadow: 3px 3px 6px #ddd, -3px 3px 6px #ddd;
}
.toggle:checked+.bio-title+.bio-content {
max-height: 500px;
}
.toggle:checked+.bio-title:before {
transform: rotate(90deg) !important;
}
我愿意使用JavaScript之类的东西,但最好只保留此CSS。后者有可能吗?
答案 0 :(得分:3)
最简单的解决方案是更改ID。
.toggle {
display: none;
}
.option {
position: relative;
margin-bottom: 1em;
}
.bio-content {
max-height: 0;
overflow: hidden;
background-color: #fff;
transition: max-height 1s ease;
}
.toggle:checked+.bio-title+.bio-content {
max-height: 500px;
}
<div class="option">
<input type="checkbox" id="toggle" class="toggle" />
<label class="bio-title" for="toggle">
Learn more
</label>
<div class="bio-content">
<p>Content</p>
</div>
</div>
<div class="option">
<input type="checkbox" id="toggle2" class="toggle" />
<label class="bio-title" for="toggle2">
Learn more
</label>
<div class="bio-content">
<p>Content</p>
</div>
</div>
在您的情况下-由于尚不支持嵌套DOM选择器( )-您可以使用一个很小的JS代码段来获得相同的结果,而无需ID。
function toggleTab(el) {
// Get the first .toggle element of the parent
const checkbox = el.parentNode.querySelector(':scope > .toggle');
// Toggle the checked state
checkbox.checked = !checkbox.checked;
}
.toggle {
display: none;
}
.option {
position: relative;
margin-bottom: 1em;
}
.bio-content {
max-height: 0;
overflow: hidden;
background-color: #fff;
transition: max-height 1s ease;
}
.toggle:checked+.bio-title+.bio-content {
max-height: 500px;
}
<div class="option">
<input type="checkbox" class="toggle" />
<label class="bio-title" onclick="toggleTab(this)">
Learn more
</label>
<div class="bio-content">
<p>Content</p>
</div>
</div>
<div class="option">
<input type="checkbox" class="toggle" />
<label class="bio-title" onclick="toggleTab(this)">
Learn more
</label>
<div class="bio-content">
<p>Content</p>
</div>
</div>