您的位置:首页 > Web前端 > JavaScript

根据已知数据生成柱状图(自定义柱状图)

2017-03-11 05:33 253 查看
如有错误,还望指出~~

一、效果



二、说明

需要注意的是外层一定要设置高宽,因为柱状图是根据百分比来生成的

因为是百分比,所以会自适应屏幕

柱型的多少根据arr.length来做的判断

每个柱状的颜色,效果都可以在js里面做调整

恩,上面都在说废话

三、代码

html:

<body>
<div class="box">
<div class="main">
// 这里的span标签最好还是根据arr.length用js来动态生成
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<div class="mask">
<i></i>
<i></i>
<i></i>
</div>
</div>
</div>
<body>


css

.box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
}

.main{
position: relative;
display: flex;
align-items: flex-end;
width: 95%;
height: 400px;
margin: 0 auto;
font-size: 0;
padding: 0;
}

.main span {
width:4%;
height: 0;
border-right: 4px solid;
transition: height 1s ease-in-out;
}

/*.mask{
position: absolute;
bottom: 0;
height: 100%;
width: 100%;
z-index: -1
}
.mask i {
display: inline-block;
height: 100%;
opacity: .5;
}

.mask i:nth-child(1) {
background-color: #ccc;
}
.mask i:nth-child(2) {
background-color: #999;
}
.mask i:nth-child(3) {
background-color: #555;
}*/


jq

$(document).ready(function () {
// 此处为自定义的数据
var arr = [20, 30, 40, 45, 60, 80, 90, 110, 150, 130, 70, 120, 140, 90, 70, 80, 50, 110, 140, 120, 60, 50, 40, 30, 20]
var maxH = 0
var line = $('.main span')
var mask = $('.mask i')
for (var i=0; i<arr.length; i++) {
if (arr[i] > maxH) {
maxH = arr[i];
}
}
// react里面用map,参数是m在前i在后
line.map(function(i, m){
if (i<12){
$(m).css({'background-color': '#ccc','border-color': '#fff'})
$(mask).eq(0).css('width', (12 * 4) + '%')
} else if (i<10) {
$(m).css({'background-color': '#ccc','border-color': '#fff'})
$(mask).eq(1).css('width', (10 * 4) + '%')
} else {
$(m).css({'background-color': '#ccc','border-color': '#fff'})
$(mask).eq(2).css('width', (3 * 4) + '%')
}

var averH = arr[i] / maxH * 100 + '%'
setTimeout(function() {
$(m).css('height', averH)
}, 500);
})
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息