JS基础实现瀑布流效果【附源码】

话不多说,直接上代码。如下:
CSS部分:

<style>
    .cont{margin: 0 auto;position: relative;}
    .box{float: left;padding: 4px;}
    .imgbox{ padding: 4px;}
    .imgbox img{width: 200px;display: block;border-radius: 4px;}
</style>

HTML部分(图片可自行添加):

<div class="cont">
    <div class="box">
        <div class="imgbox">
            <img src="../img/WaterF2.jpg" alt="">
        </div>
    </div>
    <div class="box">
        <div class="imgbox">
            <img src="../img/WaterF1.jpg" alt="">
        </div>
    </div>
   // ...
 </div>

JS部分:

<script>
    onload = function(){
        var wf = new WaterF();
        wf.init();
    }
    class WaterF{
        constructor(){
            this.clientW = document.documentElement.clientWidth;
            this.abox = document.querySelectorAll(".box");
            this.cont = document.querySelector(".cont");
        }
        init(){
            // 根据屏幕的宽度 / 任意一个结构的宽度,得到一行最多能放多少个图片
            this.maxNum = parseInt(this.clientW / this.abox[0].offsetWidth);
            // 根据一行能放置的个数 * 任意一张图片的宽度,得到了外框的真正的宽度
            this.cont.style.width = this.maxNum * this.abox[0].offsetWidth + "px";
            // 完善布局之后,开始区分第一行和后面的行
            this.firstLine();
            this.otherLine();
        }
        firstLine(){
            // 第一行,获取所有元素的高度放在一个数组中,准备获取最小值
            this.heightArr = [];
            for(var i=0;i<this.maxNum;i++){
                this.heightArr.push(this.abox[i].offsetHeight);
            }
        }
        otherLine(){
            // 需要拿到后面行的所有元素
            for(var i=this.maxNum;i<this.abox.length;i++){
                var min = getMin(this.heightArr);
                var minIndex = this.heightArr.indexOf(min);
                // 设置定位
                this.abox[i].style.position = "absolute";
                // 根据最小值设置top
                this.abox[i].style.top = min + "px";
                // 根据最小值的索引设置left
                this.abox[i].style.left = minIndex * this.abox[0].offsetWidth + "px";
                // 修改最小值为,原来的数据+当前新放置元素的高度
                this.heightArr[minIndex] = this.heightArr[minIndex] + this.abox[i].offsetHeight;
            }
        }
    }
    function getMin(arr){
        var myarr = [];
        for(var j=0;j<arr.length;j++){
            myarr.push(arr[j]);
        }
        return myarr.sort((a,b)=>a-b)[0];
    }
</script>

效果:
在这里插入图片描述

发布了40 篇原创文章 · 获赞 137 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42881768/article/details/104683516