我正在尝试使用 HTML 和 CSS 绘制垂直树状结构。我在某种程度上做到了。
<!--
We will create a family tree using just CSS(3)
The markup will be simple nested lists
-->
<div class="tree">
<ul>
<li>
<a href="#">Parent</a>
<ul>
<li><a href="#">Child</a>
<ul>
<li><a href="#">Grand Child</a></li>
</ul>
</li>
<li>
<a href="#">Child</a>
<ul>
<li><a href="#">Grand Child</a></li>
<li><a href="#">Grand Child</a>
<ul>
<li><a href="#">Great Grand Child</a></li>
<li><a href="#">Great Grand Child</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
在我的例子中,一个节点最多可以有 2 个子节点,不能超过这个数量。我让它为第一个子节点工作。如果是第二个 child ,我不会让垂直线达到 100%(直到其父节点)。
我试过做一些调整,但没有一个奏效。我可以对我的 CSS 进行哪些更改,以使其所有节点都连接起来并看起来像一棵树?
是否可以用 CSS 本身来做?还是可以通过添加一些 javascript 来实现?
最佳答案
如果您的可能性有限并且不想寻找非常动态的东西,您可以做的一件事是添加具有不同 top
的类。和 height
为你的:after pseudo element
并在你的 html 中应用类给你 li
元素取决于每个人的需要。例如:
.tree li::after{
content: '';
position: absolute; top: 0;
width: 3%; height: 50px;
right: auto; left: -2.5%;
border-bottom: 1px solid #ccc;
border-left: 1px solid #ccc;
border-radius: 0 0 0 5px;
-webkit-border-radius: 0 0 0 5px;
-moz-border-radius: 0 0 0 5px;
}
.tree li.two-step::after{
top: -100px;
height: 150px;
}
.tree li.three-step::after{
top: -180px;
height: 230px;
}
https://jsfiddle.net/g2ue3wL5/1/
编辑:
处理 :after pseudo-elements
动态不是那么容易(至少对我来说不是......)。没有办法直接处理它们,你必须通过它们的实际元素,即使那样你也需要使用 CSS
.所以动态解决方案 :after
我认为这不是最好的方法。
但您可以将它们替换为 span
, 并与 jQuery
一起工作.这为您提供了一个相对较小且简单的解决方案。首先,为每个 a 元素添加一个 span:
<li><a href="#">Child</a> <span></span>
<li><a href="#">Grand Child</a><span></span>
然后,在您的 CSS 中将 :after 替换为 > span:
.tree li > span {
content:'';
position: absolute;
top: 0;
width: 3%;
height: 50px;
right: auto;
left: -2.5%;
border-bottom: 1px solid #ccc;
border-left: 1px solid #ccc;
border-radius: 0 0 0 5px;
-webkit-border-radius: 0 0 0 5px;
-moz-border-radius: 0 0 0 5px;
}
然后您逐一检查 span
并进行一些计算以设置 height
和 top
取决于 parent
:
$('.tree li > span').each(function () {
var thisNewTop = $(this).closest('ul').offset().top - $(this).offset().top;
var thisNewHeight = $(this).offset().top - $(this).closest('ul').offset().top + 50;
$(this).css({
top: thisNewTop,
height: thisNewHeight
});
});
https://jsfiddle.net/g2ue3wL5/3/
普通的等效解决方案 javascript
会更长,我认为这是jQuery
的情况可以节省很多时间。
关于javascript - 使用 CSS 和 HTML 的垂直树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31994536/