CSS+HTML+JQuery实现条形图

时间:2024-11-24 22:03:19

CSS+HTML+JQuery实现条形图

  在工作中遇到了写条形图的情况,因为文字,条形数量和条形图的颜色需要改变,所以不能用图片,所以决定写一个试试,写的比较简单,但毕竟是第一次,也遇到了一些问题,特意记录下来,以免忘记。

  因为该页面还需要兼容ie8,处理每个条形的间距也是一个问题。所以使用justify-content: space-around;来让每个条形两端对齐,但是并不兼容ie8,于是通过js来计算每个条形之间的margin值来控制条形能达到两端对齐的效果。

  还有一个问题是:文字无法上下居中,于是把文字单独写到一个span标签中,通过js来控制span的位置。

  具体代码如下:

 <div class="chart">
<div class="bar-div">
<span class="bar">
<span class="bar-percent" style="height:86%"><span class="num-percent">86%</span><span class="percent-subject">药学综合知识</span></span>
</span>
<span class="bar">
<span class="bar-percent" style="height:99%"><span class="num-percent">99%</span><span class="percent-subject">药学一</span></span>
</span>
<span class="bar">
<span class="bar-percent" style="height:78%"><span class="num-percent">78%</span><span class="percent-subject">药学二</span></span>
</span>
<span class="bar">
<span class="bar-percent" style="height:84%"><span class="num-percent">84%</span><span class="percent-subject">中药学综合知识</span></span>
</span>
<span class="bar">
<span class="bar-percent" style="height:60%"><span class="num-percent">60%</span><span class="percent-subject">中药一</span></span>
</span>
<span class="bar">
<span class="bar-percent" style="height:93%"><span class="num-percent">93%</span><span class="percent-subject">中药二</span></span>
</span>
<span class="bar">
<span class="bar-percent" style="height:80%"><span class="num-percent">80%</span><span class="percent-subject">药事管理</span></span>
</span>
</div>
</div>

html

 <style>
.chart {
width: 300px;
position: relative;
margin: 0 auto;
border-bottom: 1px solid #ccc;
} .bar {
height: 170px;
width: 20px;
position: relative;
display: inline-block;
margin: 0 7px;
} .bar-div {
justify-content: space-around;
display: flex;
padding-top: 20px;
} .bar-percent {
background-color: #24BA09;
display: inline-block;
position: absolute;
bottom:;
width: 20px;
color: #fff;
line-height: 1.2;
text-align: center;
font-size: 12px;
} .num-percent {
font-size: 10px;
color: #999;
position: absolute;
top: -13px;
left:;
} .percent-subject {
position: relative;
top: 0%;
}
</style>

css

 //提前引入jquery
<script>
window.onload=function(){
//为了兼容ie8,设置条形图的每个条形的margin值来定位
var outWidth=$('.bar-div').width();
var len=$('.bar-div .bar').length;
var width=$('.bar-div .bar').width();
var marginNum=(outWidth-len*width)/len/2-2;
$('.bar-div .bar').each(function(){
$(this).css({"margin":"0 "+marginNum+"px"});
});
//设置条形图中文字上下居中
$(".percent-subject").each(function(){
var outHeight=$(this).parent().height();
var height=$(this).height();
var result=(outHeight-height)/2;
$(this).css({"top":result+"px"});
});
}
</script>

js

  即可实现上述图中效果。