美文网首页
瀑布流学习笔记

瀑布流学习笔记

作者: 薛小皮 | 来源:发表于2019-03-12 14:15 被阅读0次
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>瀑布流布局</title>
  <style>
    .waterfall {
      max-width: 600px;
      margin: 0 auto;
    }
    .waterfall img{
      width: 100px;
      margin: 10px;
      position: absolute;
      transition: all .4s;
    }
  </style>
</head>
<body>
  <div class="waterfall">
    <img src="http://via.placeholder.com/100x100" alt="300*100">
    <img src="http://via.placeholder.com/100x70" alt="300*70">
    <img src="http://via.placeholder.com/100x150" alt="300*150">
    <img src="http://via.placeholder.com/100x250" alt="300*250">
    <img src="http://via.placeholder.com/100x80" alt="300*80">
    <img src="http://via.placeholder.com/100x90" alt="300*90">
    <img src="http://via.placeholder.com/100x120" alt="300*120">
    <img src="http://via.placeholder.com/100x210" alt="300*210">
    <img src="http://via.placeholder.com/100x230" alt="300*230">
    <img src="http://via.placeholder.com/100x100" alt="300*100">
    <img src="http://via.placeholder.com/100x70" alt="300*70">
    <img src="http://via.placeholder.com/100x150" alt="300*150">
    <img src="http://via.placeholder.com/100x250" alt="300*250">
    <img src="http://via.placeholder.com/100x80" alt="300*80">
    <img src="http://via.placeholder.com/100x90" alt="300*90">
    <img src="http://via.placeholder.com/100x120" alt="300*120">
    <img src="http://via.placeholder.com/100x210" alt="300*210">
    <img src="http://via.placeholder.com/100x230" alt="300*230">
  </div>
  
  <script>
   var colCount//内容列数
   var colHeightArray = []//每一列高度集合
   var imgWidth = $('.waterfall img').outerWidth(true)//图片宽度
   
   colCount = Math.floor($('.waterfall').width()/imgWidth)
   for(var i = 0;i < colCount;i++){
     colHeightArray[i] = 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)
   })
  
  </script>
</body>
</html>

相关文章

网友评论

      本文标题:瀑布流学习笔记

      本文链接:https://www.haomeiwen.com/subject/mjagpqtx.html