1

我对 css 和 javascript 完全陌生,需要一些帮助来构建条形图。除其他外,我的问题是我需要在盒子 DIV 内自动调整条形 DIV 的宽度。因此,如果“元素”列表中有 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;
}
4

1 回答 1

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);

查看这些现场演示

http://jsfiddle.net/Y3ZzT/

http://jsfiddle.net/dWjGr/

于 2012-11-10T12:55:51.100 回答