需求描述
实现横向树状图效果,其中右侧子项支持点击后跳转页面:
如果只是需要实现树图效果,可以使用echarts树图 (echarts完全支持鼠标事件,非常便捷。。有空补上使用echarts树图实现的代码) ;这里需要每个子项支持点击,且个人想实现试试需要自由定义节点样式,考虑用纯CSS实现树图效果。
布局透视
观察效果树图,可以看到其中的对称结构较多(使用flex布局可以很方便地实现各种div对齐效果):
1、图表标题需与右侧子项水平居中对齐;
2、右侧子项需要在垂直方向等距分布;
3、图表的连线与连接项需要垂直居中分布
↑↑↑此图使用Visio绘制↑↑↑
代码
可以到菜鸟教程HTML在线工具粘贴代码执行查看效果
HTML
<!-- HTML代码 -->
<div class="chartBg">
<div class="chartHead">
<div class="chartHeadName">
图表标题
</div>
<div class="chartLine"></div>
</div>
<div class="chartItems">
<!-- firstItem:第一个子项相对右侧整体div的向上偏移量 -->
<!-- lastItem:最后的子项相对右侧整体div的向下偏移量 -->
<!-- 若图表只有一个子项(即:既是第一个子项也是最后的子项)时 -->
<!-- 唯一子项需要同时加上firstItem和lastItem -->
<!--
<div class="chartItem firstItem lastItem">
<div class="chartLine"></div>
<div class="chartItemName">
图表唯一子项
</div>
</div>
-->
<div class="chartItem firstItem">
<div class="chartLine"></div>
<div class="chartItemName">
图表分支1
</div>
</div>
<div class="chartItem">
<div class="chartLine"></div>
<div class="chartItemName">
图表分支2
</div>
</div>
<div class="chartItem lastItem">
<div class="chartLine"></div>
<div class="chartItemName">
图表分支3
</div>
</div>
</div>
</div>
CSS
/* CSS代码 */
.chartBg {
width: 640px;
height: 320px;
background: #acacac;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.chartHead, .chartItem {
display: flex;
flex-direction: row;
align-items: center;
justify-content: start;
}
.chartItems {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
border-left: 4px solid green;
}
.chartHeadName {
width: 120px;
text-align: center;
color: white;
background: grey;
font-size: 28px;
padding: 8px 10px;
}
.chartItemName {
height: 28px;
line-height: 28px;
background: yellow;
font-size: 22px;
padding: 4px 6px;
border: 2px solid green;
border-radius: 6px;
margin: 20px 0;
}
.chartLine {
background: green;
height: 4px;
min-width: 80px;
}
/* 第一个子项相对右侧整体div的向上偏移量 */
.firstItem {
margin-top: -38px;
}
/* 最后的子项相对右侧整体div的向下偏移量 */
.lastItem {
margin-bottom: -38px;
}
/* 鼠标指针悬停时呈现可点击的光标形状 */
.chartItem:hover {
cursor: pointer;
}
flex调试技巧
在Chrome浏览器中,使用开发者工具->元素,选中页面div后可直接调试样式
注意:在开发者工具中调试出预期的页面效果后,需将样式覆盖本地代码,否则页面刷新后将“一夜回到解放前”-_-||
补充
其实可以不用新增firstItem、lastItem来指定chartItem的第一项、最后一项的样式,可以使用CSS选择器指定样式,好处是不用再额外为第一项、最后一项增加特别的样式类名:
/* firstItem可以使用first-child选择器改写为如下形式,这样写无需再在div中添加类名 */
.chartItem:first-child {
margin-top: -38px;
}
/* lastItem可以使用last-child选择器改写为如下形式,这样写无需再在div中添加类名 */
.chartItem:last-child {
margin-bottom: -38px;
}
关于CSS选择器的使用,可以参考这篇博客:nth-child的使用方法,写得非常详细易懂~☆▽☆~。
参考文档
[1] echarts树图
[2] flex布局
[3] 菜鸟教程HTML在线工具
[4] 鼠标指针的光标形状
[5] margin和padding的用法
[6] 盒子模型
[7] CSS选择器
[8] nth-child的使用方法