jQuery和原生实现瀑布流

229 阅读1分钟

关于瀑布流

  1. 需求:1. 图片不变形, 2.占满所有空白区域
  2. 思路分析: 使用定位来实现瀑布流,首先在第一排图片不需要使用定位,只用浮动就可以了,在第二排图片,使用浮动,首先找到第一排中高度最小的那张图片,然后将第二排第一张图片就放在该图片的,图片的top值就是上面图片的高,left值就是上面图片的索引号乘以图片的宽度,具体的可以结合下面的图理解

image.png

第二排的第一个图片并不是按照我们平时想的那样从左到右的排布,而是放在第一排高度最小的图片的下方,第一个图片放好后进行,一个高度的叠加,后面一样继续寻找最小高度,以此类推。本人描述的可能不太好,如果看完还不懂,可以先去看视频,视频地址:www.bilibili.com/video/BV1oJ…

jquery实现

  <div class="main">
    
    
    <div class="box">
        <img src="img/5(3).jpg" alt="">
    </div>
  
    <div class="box">
        <img src="img/5(5).jpg" alt="">
    </div>
    <div class="box">
        <img src="img/5(2).jpg" alt="">
    </div>
    <div class="box">
        <img src="img/5(6).jpg" alt="">
    </div>
    <div class="box">
        <img src="img/5(4).jpg" alt="">
    </div>
    <div class="box">
        <img src="img/5(1).jpg" alt="">
    </div>
   </div>
   <script src="js/jquery-3.6.0.min.js"></script>
   <script>
 $(function(){
            var box = $('.box')
        // 获得列数
        var boxWidth = box.outerWidth();
        console.log(boxWidth)
       //获得当前屏幕的宽度
       var windowWidth = $(window).outerWidth();
       console.log(windowWidth)
       var line = parseInt(windowWidth / boxWidth);
        console.log(line)
    //   创建数组
        var myArr = [];
    //一次遍历每张图片 
    $.each(box,function(index,item){
        var itemHeight = $(item).outerHeight()
        console.log(itemHeight)
        //判断第一排的图片不需要进行定位
        if(index < line){
            var imgHeight = $(item).outerHeight();
            myArr.push(imgHeight)
            
        }else{
            var min = Math.min(...myArr);
            var minIndex = myArr.indexOf(min)
            $(item).css({
                position:'absolute',
                // left:高度最小的索引号 * 300,
                left : minIndex * boxWidth + 'px',
                top: min + 'px',
            })
            //高度的追加
            myArr[minIndex]+=$(item).height();
        }
    })
        })
        </script>

原生代码实现

let box = document.getElementsByClassName('box');
       let boxWidth = box[0].clientWidth;
       console.log(boxWidth)
       let windowWidth = document.body.clientWidth;
       // let windowWidth = document.documentElement.clientWidth
       let line = parseInt(windowWidth / boxWidth);
       let myArr = [];
       console.log(box)
       for(let i = 0;i < box.length;i++){
           let itemHeight = box[i].clientHeight;
           if(i < line){
               myArr.push(itemHeight);
               console.log(myArr)
           }else{
               let min = Math.min(...myArr);
               let minIndex = myArr.indexOf(min);
               box[i].style.position = 'absolute',
               box[i].style.left = minIndex * boxWidth + 'px',
               box[i].style.top = min + 'px'
               myArr[minIndex] += itemHeight;
           }
       }