本文实例讲述了jQuery制作简单柱状图的方法。分享给大家供大家参考。具体实现方法如下:
Html部分:
CSS部分:
Js部分:
function histogram(){
var controls={};
var bgColor=new Array("#666666","#21AA7C","#2277BB","#dc7644","#BBAA22","#AA22AA","#338800","#1099EE","#ffcc33","#ED3810");
this.init=function(data,y){
setControls();
buildHtml(data,y);
}
function setControls(){
controls.histogramContainer=$("#histogram-container");
controls.histogramBgLineUL=controls.histogramContainer.children("div.histogram-bg-line");
controls.histogramContentUL=controls.histogramContainer.children("div.histogram-content");
controls.histogramY=controls.histogramContainer.children("div.histogram-y");
}
function buildHtml(data,y){
var len=data.length,perArr=new Array(),maxNum,maxTotal,yStr='';
var contentStr='',bgLineStr='',bgLineAll='';
var widthPer=Math.floor(100/len);
minWidth=len*21+60;
controls.histogramContainer.css("min-width",minWidth+"px");
for(var a=0;a<len;a++){
perArr[a]=parseInt(data[a]['per']);
}
maxNum=String(perArr.max());
if(maxNum.length>2){
var x=parseInt(maxNum.substr(maxNum.length-2,1))+1;
maxTotal=Math.floor(parseInt(maxNum/100))100+x10;
}else{
maxTotal=Math.floor(parseInt(maxNum/10))*10+10;
}
//y轴部分
if(y=="%"){
yStr+='
}else{
var avg=maxTotal/5;
for(i=5;i>=0;i--){
yStr+='
}
}
//柱状条部分
for(var i=0;i<len;i++){
var per=Math.floor(parseInt(data[i]['per'])/maxTotal*100);
var n=Math.floor(parseInt(per)/10);
contentStr+='<li style="width:'+widthPer+'%">';
contentStr+='<span class="histogram-Box"><a style="height:'+per+'%'+';background:'+bgColor[n]+';" title="'+data[i]['per']+'"><span class="histogram-name">'+data[i]['name']+'';
contentStr+='';
bgLineStr+='<li style="width:'+widthPer+'%;">
}
//背景方格部分
for(var j=0;j<5;j++){
bgLineAll+='
- '+bgLineStr+'
}
bgLineAll='<div class="histogram-bg-line">'+bgLineAll+'
contentStr='<div class="histogram-content">
- '+contentStr+'
yStr='<div class="histogram-y">
- '+yStr+'