前端基础(四十):实现页面的瀑布流式布局

效果、原理

在这里插入图片描述

源码

* {
    
    
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    outline: none;
}

html,
body {
    
    
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
}

#app {
    
    
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: auto;
}

.pic-item {
    
    
    position: absolute;
    border: 1px solid #000;
}
<div id="app">
    <!-- <img class="pic-item" :src="item" width="200"> -->
</div>
// 添加img标签
const root = document.getElementById('app');
for (let i = 1; i <= 20; i++) {
    
    
    const color = ()=>{
    
    
        let c = '0123456789abcdef'.split('');
        return c[Math.floor(Math.random(0, 1) * 15)];
    }
    let h = Math.floor(Math.random() * 500) + 50;
    let img = document.createElement("img");
    img.className = 'pic-item';
    img.width = 200;
    img.src = `https://dummyimage.com/200x${
      
      h}/${
      
      color()}${
      
      color()}${
      
      color()}/fff?text=200x${
      
      h} ${
      
      i}`;
    root.appendChild(img);
}

// 监听页面当前加载状态
document.onreadystatechange = () => {
    
    
    // 页面加载完成
    if (document.readyState === 'complete') {
    
    

        // 瀑布流
        const picList = document.getElementsByClassName('pic-item');

        // 单张图片宽度
        const w = 200;
        // 定义列数
        const col = 5;

        // 获取第一列图片高度集合
        let heightList = [...picList].slice(0, col).map(el => el.offsetHeight);
        console.log(`第一行 ${
      
      col} 个 图片标签的高度`, heightList);

        // 循环标签
        for (let i = 0; i < picList.length; i++) {
    
    

            // 当前标签
            let ele = picList[i];

            // 第一行(不做处理按原样顺序定位输出)
            if (i < col) {
    
    
                // 修改定位
                ele.style.top = '0px';
                ele.style.left = `${
      
      w * i}px`;
            }

            // 其他行(做处理,按每次获取到的最低高度进行样式定位)
            else {
    
    
                // 找出最小高度
                let minHeight = Math.min.apply(null, heightList);
                // 判断最小高度在数组中的下标(第几列的图片)
                let j = heightList.indexOf(minHeight);

                // 修改定位放到最小的标签的位置的下方
                ele.style.top += `${
      
      minHeight}px`;
                ele.style.left = `${
      
      w * j}px`;

                // 修改定位(修改最小的那个高度为加上当前元素的高度,用于下次循环时判断出另一个最小高度)
                heightList[j] += ele.offsetHeight;
                console.log('修改最小高度后新的高度集合', heightList);
            }

        }

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43526371/article/details/125693257