输入一个数字,随机生成柱形图

304 阅读1分钟

允许用户输入一个数字,根据用户数字制作如下效果 要求1:柱子的数量根据用户的输入数确定 要求2:柱子的高度随机 要求3:柱子的颜色随机 要求4:柱子间的间隔与柱子的宽度是一样的

 <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }



        .box {
            display: flex;
            justify-content: space-evenly;
            align-items: flex-end;
            width: 1000px;
            height: 200px;
            border: 1px solid #0a0;
            margin: 100px auto;
        }
    </style>
    //用户输入柱子的数量
        let num = +prompt('请输入数字')
        //数字的合法性
        if (num > 0 && num % 1 == 0) {
            //柱子的宽度计算
            let w = 1000 / (2 * num + 1)

            //输入一半的父盒子
            document.write(`<div class = "box">`)

            for (let i = 0; i < num; i++) {
                //生成随机高度
                let h = Math.ceil(Math.random() * 200)
                //随机背景色
                let r = Math.round(Math.random() * 255)
                let g = Math.round(Math.random() * 255)
                let b = Math.round(Math.random() * 255)
                //生成子盒子
                document.write(`<div class = "box2" style = "width:${w}px;height:${h}px;background:rgb(${r},${g},${b});"></div>`)
            }
            //另一半的父盒子
            document.write('</div>')
        } else {
            alert('重新输入')
        }