Nag*_*aga 7 html javascript css jquery css3
我试图用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>
Run Code Online (Sandbox Code Playgroud)
在我的例子中,一个节点最多可以有2个子节点,不超过这个节点.我让它为第一个子节点工作.在第二个孩子的情况下,我没有得到100%的垂直线(直到其父节点).
我试过做一些调整,但没有一个工作.我可以将什么更改为我的CSS,因此它将连接所有节点并看起来像一棵树?
是否可以使用CSS本身?或者是否可以通过添加一些JavaScript?
如果您的可能性有限,并且不寻找非常动态的东西,那么您可以做的一件事是为您添加具有不同的top和 的类,并根据每种需要将 html 中的类应用于您的元素。例如这样的事情:height:after pseudo elementli
.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;
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
然后,在 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;
}
Run Code Online (Sandbox Code Playgroud)
然后您仔细检查每一个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
});
});
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/g2ue3wL5/3/
简单的等效解决方案会更长,我认为这是可以节省大量时间javascript的情况。jQuery