JavaScript 生成瀑布流布局

1585364631
2023-03-05 / 0 评论 / 157 阅读 / 正在检测是否收录...

JavaScript 生成瀑布流布局

<!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>JavaScript实现瀑布流布局</title>
    <style>
        .box {
            display: grid;
            width: 100%;
            position: relative;
            grid-gap: 20px;
            align-items: start;
        }
    </style>
</head>
<body>
    <input type="text" placeholder="输入高" id="text" />
    <input type="button" value="点我添加新元素" id="button" />
    <div class="box" id="box"></div>
    <script>
        const color0x = () => {
            return `#${Math.floor(Math.random() * 256).toString(16).padStart(2, '0')}${Math.floor(
                Math.random() * 256
            ).toString(16).padStart(2, '0')}${Math.floor(Math.random() * 256).toString(16).padStart(2, '0')}`;
        };
        const ids = []
        const column = 2
        const box = document.getElementById("box")
        const button = document.getElementById("button")
        const text = document.getElementById("text")
        window.onload = () => {
            box.style.gridTemplateColumns = `repeat(${column}, 1fr)`
            for (const item of Array.from(new Array(column).keys())) {
                let div = document.createElement("div")
                div.style.width = "100%"
                div.id = "div" + item
                box.append(div)
                ids.push(div)
            }
            button.onclick = () => {
                let min = ids[0].offsetHeight
                let id = 0;
                for (let i = 1; i < ids.length; i++) {
                    if (ids[i].offsetHeight < min) {
                        min = ids[i].offsetHeight
                        id = i
                    }
                }
                let div = document.createElement("div")
                div.style.width = "100%"
                div.style.height = text.value + "px"
                div.style.margin = "5px"
                div.style.backgroundColor = color0x()
                ids[id].appendChild(div)
            }
        }
    </script>
</body>
</html>
0

评论 (0)

取消