2021-05-14 12:09:20
以下是5种无需JavaScript、仅使用CSS实现统计图的方案及详细说明:
1. 柱状图(Bar Chart)实现原理:通过div元素的height属性控制柱子高度,结合Flex布局实现横向排列。代码示例:
<div class="bar-chart"> <div class="bar" style="height: 60%;"></div> <div class="bar" style="height: 80%;"></div> <div class="bar" style="height: 40%;"></div></div><style> .bar-chart { display: flex; width: 300px; height: 200px; border-bottom: 1px solid #ccc; align-items: flex-end; } .bar { width: 20px; background-color: steelblue; margin-right: 5px; transition: height 0.5s ease-in-out; /* 添加动画效果 */ }</style>效果:

实现原理:利用transform: rotate()和clip属性模拟扇形,通过绝对定位叠加多个div。代码示例:
<div class="pie-chart"> <div class="slice" style="--angle: 60; background-color: red;"></div> <div class="slice" style="--angle: 120; background-color: green;"></div></div><style> .pie-chart { width: 200px; height: 200px; border-radius: 50%; overflow: hidden; position: relative; } .slice { width: 200px; height: 200px; clip: rect(0, 200px, 200px, 100px); position: absolute; transform-origin: 0 50%; transform: rotate(calc(var(--angle) * 1deg)); }</style>效果:

实现原理:用div模拟数据点,通过border或linear-gradient连接线段(实现复杂)。简化方案:
<div class="line-chart"> <div class="point" style="--x: 20%; --y: 30%;"></div> <div class="point" style="--x: 50%; --y: 60%;"></div></div><style> .line-chart { width: 300px; height: 200px; position: relative; background: linear-gradient(to right, transparent 19%, steelblue 19%, steelblue 21%, transparent 21%), linear-gradient(to right, transparent 49%, steelblue 49%, steelblue 51%, transparent 51%); } .point { width: 10px; height: 10px; background-color: red; border-radius: 50%; position: absolute; left: var(--x); top: var(--y); transform: translate(-50%, -50%); }</style>特点:
实现原理:在饼图基础上叠加一个白色圆形,形成空心效果。代码示例:
<div class="donut-chart"> <div class="pie-inner"> <div class="slice" style="--angle: 90; background-color: orange;"></div> </div> <div class="donut-hole"></div></div><style> .donut-chart { width: 200px; height: 200px; position: relative; } .pie-inner { width: 100%; height: 100%; border-radius: 50%; overflow: hidden; position: relative; } .donut-hole { width: 120px; height: 120px; background-color: white; border-radius: 50%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }</style>特点:
实现原理:通过width属性控制填充比例,结合background渐变增强视觉效果。代码示例:
<div class="progress-bar"> <div class="progress" style="width: 75%;"></div></div><style> .progress-bar { width: 300px; height: 20px; background-color: #eee; border-radius: 10px; overflow: hidden; } .progress { height: 100%; background: linear-gradient(to right, #4CAF50, #8BC34A); transition: width 1s ease-in-out; }</style>特点:
适用场景:静态数据展示、简单可视化需求或对性能要求极高的环境。复杂场景建议使用JavaScript库(如Chart.js、D3.js)。