解释:
该示例是把柱子对应的数据直接进行的赋值。
如果需要用ajax从后台请求数据,只需要增加ajax请求部分即可。我在下一个示例中会写
效果图:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
#box{
position: relative;
left:100px;
width: 800px;
height: 500px;
border: 1px solid black;
}
</style>
</head>
<body>
<input id="btnGet" type="button" value="获得数据" />
<div id="box">
</div>
</body>
</html>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
function $create(str){
return document.createElement(str);
}
//前端和后端需要交流的信息:
//请求方式:get
//地址:getTotalSale.php
//请求参数;yearCount:最近几年
//返回数据的格式:
/*
[
{
year:2016,
money:800
},
{
year:2015,
money:600
},
{
year:2014,
money:500
}
]
*/
let jsonArr = [
{
year:2011,
money:200
},
{
year:2012,
money:400
},
{
year:2013,
money:450
},
{
year:2014,
money:500
}
,
{
year:2015,
money:600
},
{
year:2016,
money:800
},
{
year:2017,
money:850
}
];
//柱子的颜色数组
let colorArr=["red","green","yellow","blue","pink","orange","gray","purple"];
function getMaxMoney(jsonArr){
let max = jsonArr[0].money;
for(let i=1;i<jsonArr.length;i++){
if(jsonArr[i].money>max){
max = jsonArr[i].money;
}
}
return max;
}
function showData(jsonArr){
$("box").innerHTML="";
//最大金额
let maxMoney = getMaxMoney(jsonArr);
//大容器的高度-50;
let maxHeight = 500-50;
//比例(金额像素比)
let rate=maxHeight/maxMoney;
//留白的宽度
let spaceWidth = 800/(jsonArr.length*2+1);
if(spaceWidth>80){
spaceWidth = 80;
}
//柱子的宽度
let zhuWidth = 800/(jsonArr.length*2+1);
if(zhuWidth>80){
zhuWidth = 80;
}
for(let i=0;i<jsonArr.length;i++){
//放置金钱,颜色柱子,年份的容器
let contentDom = $create("div")
let left = (i+1)*spaceWidth+i*zhuWidth;//
contentDom.style.cssText = "position: absolute; bottom: -30px;left:"+left+"px;";
$("box").appendChild(contentDom);
//放置金额的span元素
let moneySpanDom = $create("span");
moneySpanDom.innerHTML = jsonArr[i].money;
moneySpanDom.style.cssText = "display: block;height: 20px;width: 80px;text-align: center;";
contentDom.appendChild(moneySpanDom);
//颜色柱子
let colorPillDom = $create("div")
let height = jsonArr[i].money*rate;
colorPillDom.style.cssText ="width: "+zhuWidth+"px;height: "+height+"px;background-color:"+colorArr[i%colorArr.length]+";";
contentDom.appendChild(colorPillDom);
//放置年份的span元素
let yearSpanDom = $create("span");
yearSpanDom.innerHTML = jsonArr[i].year;
yearSpanDom.style.cssText = "display: block;height: 30px;width: 80px;text-align: center;";
contentDom.appendChild(yearSpanDom);
}
}
window.onload = function(){
$("btnGet").onclick = function(){
showData(jsonArr);
}
}
</script>
注:
可以给jsonArr中增加一个元素,试试效果是否会增加一个柱子。