zl程序教程

您现在的位置是:首页 >  后端

当前栏目

原生JS-根据数据生成柱形图

JS数据 生成 原生 根据 柱形图
2023-06-13 09:18:28 时间

需求:

用户输入四个季度的数据,可以生成柱形图。

效果图

分析

  1. 需要输入4次,所以可以把4个数据放到一个数组里面
    • 利用循环,弹出4次框,同时存到数组里面
  2. 使用
var div1 = document.getElementById('one')

得到第一个div的id名 one。 3. 使用

div1.style.height = `${Data[0]}px`

给类名为 one 的div添加高度。 4.

div1.innerHTML = Data[0] + '<br>' + '第1季度'

给id名为one的div添加内容。

代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>根据数据生成柱状图</title>
    <style>
        .box {
            margin: 30px auto;
            width: 700px;
            height: 100%;
            display: flex;
            justify-content: space-around;
            align-items: flex-end;
            border-left: 3px solid black;
            border-bottom: 3px solid black;
        }

        #one {
            width: 60px;
            text-align: center;
            background-color: #4f1;
        }

        #two {
            width: 60px;
            text-align: center;
            background-color: #a41;
        }

        #three {
            width: 60px;
            text-align: center;
            background-color: #849;
        }

        #four {
            width: 60px;
            text-align: center;
            background-color: #0aa;
        }
    </style>
</head>

<body>
    <div class="box">
        <div id="one"></div>
        <div id="two"></div>
        <div id="three"></div>
        <div id="four"></div>
    </div>
    <script>
        let Data = []
        let Div = []
        let Name = ["one","two","three","four"]
        for (let i = 0; i < 4; i++) {
            /* 将每一季度的数据添加到Data数组中 */
            Data.push(prompt(`请输入第${i+1}季度数据`))
            /* 得到div的类名 */ 
            Div[i] = document.getElementById(Name[i])
        }
        for (let i = 0; i < 4; i++) {
            /* 给div设置高度,高度 = 当前季度数据的大小 */
            Div[i].style.height = `${Data[i]}px`
            /* 给div添加内容 */
            Div[i].innerHTML = Data[i] + '<br>' + `第${i+1}季度`
        }
    </script>
</body>

</html>