js瀑布流

2020-02-13  本文已影响0人  前端来入坑
$(window).on('load', function() {
    waterFall();
});
function waterFall() {
    var box = $('.box');
    var boxWidth = box.outerWidth(); //当前图片的宽度 outerWidth() innerWidth() width();
    var screenWidth = $(window).width();
    var cols = parseInt(screenWidth/boxWidth);//求出列数
    var heightArr = [];//存储每列高度的数组
    $.each(box, function(index, item) {
        var boxHeight = $(item).outerHeight();
        if(index < cols) { //第一行
            heightArr[index] = boxHeight;
        }else{
            //数组中高度最小值的索引, 用于最小图片高度下面放置图片
            var minBoxHeight = Math.min(...heightArr);
            var minBoxIndex = heightArr.findIndex((item, index) => {
                return item == minBoxHeight;
            });
            // var minBoxHeight = $.inArray(minBoxHeight, heightArr);//jq写法
            $(item).css({
                position: 'absolute',
                left: minBoxIndex*boxWidth + 'px',
                top: minBoxHeight + 'px'
            });
            // 更改数组的高度
            heightArr[minBoxIndex] += boxHeight;
        }
    });
    console.log(heightArr);
}
//页面窗口变化重新执行函数
window.addEventListener('resize', function() {
    let timer = setTimeout(function() {
        clearInterval(timer);
        waterFall();
    }, 100);
})

html

<div id="content">
    <div class="box"><img src="./images/1.gif" alt=""></div>
    <div class="box"><img src="./images/2.jpg" alt=""></div>
    <div class="box"><img src="./images/3.png" alt=""></div>
    <div class="box"><img src="./images/4.jpg" alt=""></div>
    <div class="box"><img src="./images/5.png" alt=""></div>
    <div class="box"><img src="./images/6.jpg" alt=""></div>
    <div class="box"><img src="./images/7.png" alt=""></div>
    <div class="box"><img src="./images/8.jpg" alt=""></div>
    <div class="box"><img src="./images/9.jpg" alt=""></div>
    <div class="box"><img src="./images/10.jpg" alt=""></div>
    <div class="box"><img src="./images/11.jpg" alt=""></div>
    <div class="box"><img src="./images/12.jpg" alt=""></div>
    <div class="box"><img src="./images/13.jpg" alt=""></div>
    <div class="box"><img src="./images/14.jpg" alt=""></div>
    <div class="box"><img src="./images/15.jpg" alt=""></div>
    <div class="box"><img src="./images/16.jpg" alt=""></div>
    <div class="box"><img src="./images/17.jpg" alt=""></div>
    <div class="box"><img src="./images/18.jpg" alt=""></div>
</div>

css

*{
    padding: 0;
    margin: 0;
}
#content{
    font-size: 0;
}
.box{
    display: inline-block;
    width: 25%;
    padding: 20px;
    border: 1px solid orange;
    box-sizing: border-box;
    vertical-align: top;
}
.box img{
    width: 100%;
}
上一篇下一篇

猜你喜欢

热点阅读