JavaScript实现图片的瀑布流效果

在一些网站中会用到图片的瀑布流效果,图片的宽度固定而高度不固定,对这样的图片进行排列,具体实现如下:

.cont{
   margin: 0 auto;position: relative;}
.box{
   float: left;padding: 4px;}
.imgbox{
   border: solid 1px #000;padding: 4px;border-radius: 4px;}
.imgbox img{
   width: 200px;display: block;}

js写在head里,因此需要写在onload函数里:

onload = function(){
   
    var wf = new WaterF();
    wf.init();
}
class WaterF{
   
    constructor(){
   
        this.cont = document.querySelector(".cont");
        this.abox = document.querySelectorAll(".box");
        // 获取页面的宽度
        this.clientW = document.documentElement.clientWidth;
    }
    init(){
   
        // 计算得到在页面一行能放几个box
        this.maxNum = parseInt(this.clientW / this.abox[0].offsetWidth);
        // 给cont设置宽度为一个box的宽度乘一行最多放置的个数的宽度
        this.cont.style.width = this.abox[0].offsetWidth * this.maxNum + "px";

        // 完善布局之后,需要区分第一行和其他行
        // console.log(this);
        this.firstLine();
        this.otherLine();
    }
    firstLine(){
   
        // 在第一行,获取所有元素的高度,放在一个数组内,用以得到最小高度
        this.heightArr = [];
        for(var i = 0;i<this.maxNum;i++){
   
            this.heightArr.push(this.abox[i].offsetHeight);
        }
        // console.log(this.heightArr);
    }
    otherLine(){
   
        // 需要拿到后面行的所有元素
        for(var i = this.maxNum;i<this.abox.length;i++){
   
            // 获取第一行的最小值和最小值的索引
            var min = Math.min(...this.heightArr);
            // console.log(min);
            var minIndex = this.heightArr.indexOf(min);
            // console.log(minIndex);
            // 设置定位
            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;

        }
    }
}

html代码,因为需要对cont或许宽度,所以如果给box设置margin会导致宽度计算不正确,因此只能给box设置padding值才能实现图片与图片的距离,某些情况下,图片下方会添加文字,所以给图片和文字写一个共同的imgbox,本篇文章只写图片,具体代码如下:

<div class="cont">
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值