瀑布流布局

2019-08-05  本文已影响0人  学的会的前端

瀑布流布局---JS

内容的宽度是相等的,高度是随机的。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src = "http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
    <style>
        .content {
            position: relative;
        }
        .item {
            position: absolute;
            width: 200px;
            margin-right: 10px;
            margin-top: 10px;
    /*位置发生变化的时候,以一种渐变的方式移动,加上之后,有一个动画的效果*/
            transition: all 1s;
        }
        .h1 {
            height: 200px;
            background-color: #f4b300;
        }
        .h2 {
            height: 300px;
            background-color: #691bb8;
        }
        .h3 {
            height: 400px;
            background-color: #006c12;
        }
    </style>
</head>
<body>
   <div class = "content">
       <div class = "item h1">
           1
       </div>
       <div class = "item h3">
           2
       </div>
       <div class = "item h2">
           3
       </div>
       <div class = "item h1">
           4
       </div>
       <div class = "item h1">
           5
       </div>
       <div class = "item h3">
           6
       </div>
       <div class = "item h3">
           7
       </div>
       <div class = "item h2">
           8
       </div>
       <div class = "item h1">
           9
       </div>
       <div class = "item h3">
           10
       </div>
       <div class = "item h3">
           11
       </div>
       <div class = "item h3">
           12
       </div>
       <div class = "item h2">
           13
       </div>
       <div class = "item h2">
           14
       </div>
   </div> 
  
   <script>
   
    //打开页面的时候 ,直接布局
    waterfull()
    //当窗口发生变化的时候
    $(window).resize(function(){
        waterfull()
    })
    //当窗口发生变化的时候,随之重新排列
    function waterfull(){
           
        //得到元素的宽度
        var nodeWidth = $('.item').width()
        //每一行可以放的元素的个数,取整
        var colLength = parseInt($('.content').width()/nodeWidth)
        //定义一个数组,并初始化
        var itemArr = []
        for(var i = 0; i < colLength; i++){
            itemArr[i] = 0
        }
        $('.item').each(function(){
            //找到数组中的最小值
            var minValue = Math.min.apply(null,itemArr)
            //得到最小元素的下标
            var minIndex = itemArr.indexOf(minValue)
            $(this).css({
                top: itemArr[minIndex],
                //加true包括了元素的外边框
                left: $(this).outerWidth(true) * minIndex
            })
            //元素放入之后,这一列的高度发生了变化
            itemArr[minIndex] += $(this).outerHeight(true)
        })
    }

   </script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读