js实现瀑布流布局

瀑布流不是实现原理:

1.瀑布流的布局,要求布局的元素是等宽的,瀑布流布局的特点就是等宽不等高,然后计算元素的宽度和浏览器屏幕宽度的比值,确定出列数

2.创建一个数组,这个数组用于存储第一行图片的各个高度

3.计算出这个数组中最小的元素,接下来的图片通过定位的方式布局到高度最小的图片下面,

4.最后将这个最小高度进行更新,然后一直循环地布局下去

$(window).on("load", function () {
  watchFall()
})
function watchFall() {
  var boxs = $(".box")
  var boxWidth = boxs.outerWidth()
  var screenWidth = $(window).width()
  var cols = parseInt(screenWidth / boxWidth)
  //存储图片的高度
  var heightArr = []
  console.log(heightArr)
  $.each(boxs, function (index, item) {
    var imgHeight = $(item).outerHeight();
    if (index < cols) {
      heightArr[index] = imgHeight
    } else {
      //找到第一列中最小的高度,left:最小高度的索引*width top:最小高度+“px”
      var minHeight = Math.min(...heightArr)
      // console.log(minHeight)
      var minIndex = $.inArray(minHeight, heightArr)
      // console.log(minIndex)
      $(item).css({
        position: "absolute",
        left: minIndex * boxWidth + "px",
        top: minHeight + "px"
      })
      //更新最小的高度
      heightArr[minIndex] += imgHeight
      // console.log(heightArr)
    }
  })


}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值