我使用 this source 中的代码构建了一个 CSS 可折叠树结构.我做了一些更改以删除“+”和“-”图像,因为它使格式困惑,并决定使用另一个文件夹图像(打开的)显示树的扩展部分,like so .
我尝试使用 ~ 选择器在 CSS 中执行此操作,但它不起作用,因为标签就在其关联输入之前。我无法切换它,因为树不会按预期展开/收缩。
我正在探索使用 Javascript 的可能性,但由于我有大约 300 个标签-复选框对,使用 getElementbyID 来获取我要修复的确切标签似乎不可行。有没有更简单的方法来做到这一点?
HTML 代码:
<ol class="tree">
<li>
<label for="CB1">Label1</label><input type="checkbox" id="CB1" />
<ol>
<li class="file">File 1</li>
<li class="file">File 2</li>
<li class="file">File 3</li>
</ol>
</li>
</ol>
CSS 代码:
ol.tree li.file a
{
background: url(../images/document.png) 0 0 no-repeat;
color: #2D629A;
padding-left: 21px;
text-decoration: none;
display: block;
}
ol.tree li input
{
position: absolute;
opacity: 0;
z-index: 2;
cursor: pointer;
height: 1em;
width: 1em;
top: 0;
}
ol.tree li label
{
background: url(../images/folder-horizontal.png) 15px 1px no-repeat;
cursor: pointer;
display: block;
padding-left: 37px;
}
ol.tree li input:checked ~ label
{
background: url(../images/folder-open.png) 40px 5px no-repeat;
}
最佳答案
首先,<input>
元素放错地方了。
它必须在标签之前才能起作用。
其次,要使其正常工作,您需要设置 <ol>
隐藏然后在 <input>
时显示它已检查。
生成的 html:
<ol class="tree">
<li>
<input type="checkbox" id="CB1" /><label for="CB1">Label1</label>
<ol>
<li class="file">File 1</li>
<li class="file">File 2</li>
<li class="file">File 3</li>
</ol>
</li>
</ol>
新的 CSS:
ol.tree ol
{
display:none;
}
ol.tree li.file a
{
background: url(../images/document.png) 0 0 no-repeat;
color: #2D629A;
padding-left: 21px;
text-decoration: none;
display: block;
}
ol.tree li input
{
position: absolute;
opacity: 0;
z-index: 2;
cursor: pointer;
height: 1em;
width: 1em;
top: 0;
}
ol.tree li label
{
background: url(../images/folder-horizontal.png) 15px 1px no-repeat;
cursor: pointer;
display: block;
padding-left: 37px;
}
ol.tree li input:checked ~ label
{
background: url(../images/folder-open.png) 40px 5px no-repeat;
}
ol.tree li input:checked ~ ol
{
display:block;
}
在此处查看实际效果:http://jsfiddle.net/mjx8t596/1/
注意:
我没有触及图像:我保持相同的路径并且没有更改代码中的任何其他内容。
关于javascript - 在选中的输入上更改标签的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26790146/