瀑布流布局

2019-06-13  本文已影响0人  kzc爱吃梨

一、定义

宽度相同,而高度是随机的布局

二、实现方式

  1. 设置图片宽度一致,高度可以不一致(注:图片样式必须得加上position:absolute,因为js 是靠定位来控制其位置)
  2. 初始化一个数组,存储每一列的高度(数组的长度是布局的列数),并且给每个下标赋值为0
  3. 计算出一排的列表个数(容器宽度除以元素宽度)
  4. 循环每个元素, 循环的内部再循环列数组,判断哪一列元素的高度最小,就将下一个元素放到该列
  5. 再判断放入该元素之后所形成的新的整排元素内,哪一列元素最短,再把下一个元素放置该列,以此类推
  6. 最后当图片加载完成,所有图片依次放置在最小的列数下面

三、代码实现

    var colCount //定义列数
    var colHeightArray = [] //存放列的高度数组,该数组的长度为 colCount
    var imgWidth = $('.waterfall img').outerWidth(true) //单张图片宽度
    
    colCount = Math.floor($('.waterfall').width()/imgWidth) //获取列数 
    console.log(colCount)
    for(var i=0; i<colCount; i++){
      colHeightArray[i] = 0
    }
    // [0,0,0]
   
    //只有当页面中的图片资源全部加载完毕后,才能读到图片的真实高度
    $('.waterfall img').on('load', function(){
      var minValue =  colHeightArray[0]  //定义最小高度
      var minIndex = 0  //定义最小高度的下标
      //遍历 从数组找到最小值及下标
      for(var i=0; i<colCount; i++){
        if(colHeightArray[i]<minValue){
          minValue =  colHeightArray[i]
           minIndex = i
        }
      }
      
      //图片的位置
      $(this).css({
        left: minIndex * imgWidth,
        top: minValue
      })
      colHeightArray[minIndex] += $(this).outerHeight(true)
    })
    
    //窗口大小改变,图片重新排列
    $(window).on('resize', function(){
      var colHeightArr= []
      colCount = Math.floor($('.waterfall').width()/imgWidth)
      for(var i = 0 ; i < colCount; i++){
        colHeightArr[i] = 0
      }
      $('.waterfall img').each(function(){
        var minValue = colHeightArr[0]
        var minIndex = 0
        for(var i = 0 ; i < colCount; i ++){
          if(colHeightArr[i] < minValue){
            minValue = colHeightArr[i]
            minIndex = i
          }
        }
        $(this).css({
           top: minValue,
           left: minIndex*imgWidth
        })
        colHeightArr[minIndex] += $(this).outerHeight(true)
      })      
    })

效果预览

上一篇 下一篇

猜你喜欢

热点阅读