我是css和javascript的新手,需要一些建立条形图的帮助。我的问题是,我需要在我的盒子DIV中自动调整条形DIV的宽度。因此,如果“element”-list中有2个值,那么它们应该拉伸并填充DIV,但如果有10个则需要缩小。
Javascript
var element = [ 189, 128, 28, 88];
var _body = document.getElementsByTagName("body")[0];
var _div = document.createElement("div");
_div.id = "box";
_body.appendChild(_div);
var mainbox = document.getElementById("box");
for (var i=0; i <= element.length; i++){
var bars = document.createElement("div");
bars.setAttribute("class", "bar");
bars.id = "bar";
bars.style.height = element[i]+"px";
mainbox.appendChild(bars);
}
var text = document.createElement("div");
text.setAttribute("class", "text");
text.innerHTML="Mitt stapeldiagram";
mainbox.appendChild(text);
CSS 我已将“宽度”值设置为100%,但我不知道这是否正确?
.text{
font-family:"Times New Roman", Times, Sans-serif;
font-size:28px;
font-weight:bold;
color:gray;
text-align:center;
margin-top:370px;
overflow:hidden;
}
#box{
overflow:hidden;
width: 500px;
height: 400px;
margin-top:50px;
margin-left:50px;
padding:10px;
background-color:lightgray;
border-top:3px solid black;
border-right:3px solid black;
box-shadow: 10px 10px 5px #888;
}
.bar{
float:left;
position:relative;
width:100%;
margin:3px;
background-color:blue;
box-shadow: 5px 2px 5px #888;
}
答案 0 :(得分:0)
试试这个
var element = [189, 128, 28, 88];
var _body = document.getElementsByTagName("body")[0];
var _div = document.createElement("div");
_div.id = "box";
_body.appendChild(_div);
var mainbox = document.getElementById("box");
// set total box height
var mainboxHeight = 400;
// get total
var total = 0;
for (var i = 0; i < element.length; i++)
total += parseInt(element[i]);
for (var i = 0; i <= element.length; i++) {
// change elements to percentage
var elementPerc = Math.round((element[i] / total) * 100);
var bars = document.createElement("div");
bars.setAttribute("class", "bar");
bars.id = "bar";
var heightPerc = Math.round((elementPerc / 100) * mainboxHeight);
bars.style.height = heightPerc + "px";
mainbox.appendChild(bars);
}
var text = document.createElement("div");
text.setAttribute("class", "text");
text.innerHTML = "Mitt stapeldiagram";
mainbox.appendChild(text);
查看这些现场演示