1. 程式人生 > 程式設計 >JS實現瀑布流效果

JS實現瀑布流效果

本文例項為大家分享了JS實現瀑布流效果的具體程式碼,供大家參考,具體內容如下

話不多說,直接上程式碼。如下:

CSS部分:

<style>
 .cont{margin: 0 auto;position: relative;}
 .box{float: left;padding: 4px;}
 .imgbox{ padding: 4px;}
 .imgbox img{width: 200px;display: block;border-radius: 4px;}
</style>

HTML部分(圖片可自行新增):

<div class="cont">
 <div class="box">
  <div class="imgbox">
   <img src="../img/WaterF2.jpg" alt="JS實現瀑布流效果">
  </div>
 </div>
 <div class="box">
  <div class="imgbox">
   <img src="../img/WaterF1.jpg" alt="JS實現瀑布流效果">
  </div>
 </div>
 // ...
 </div>

JS部分:

<script>
 onload = function(){
  var wf = new WaterF();
  wf.init();
 }
 class WaterF{
  constructor(){
   this.clientW = document.documentElement.clientWidth;
   this.abox = document.querySelectorAll(".box");
   this.cont = document.querySelector(".cont");
  }
  init(){
   // 根據螢幕的寬度 / 任意一個結構的寬度,得到一行最多能放多少個圖片
   this.maxNum = parseInt(this.clientW / this.abox[0].offsetWidth);
   // 根據一行能放置的個數 * 任意一張圖片的寬度,得到了外框的真正的寬度
   this.cont.style.width = this.maxNum * this.abox[0].offsetWidth + "px";
   // 完善佈局之後,開始區分第一行和後面的行
   this.firstLine();
   this.otherLine();
  }
  firstLine(){
   // 第一行,獲取所有元素的高度放在一個數組中,準備獲取最小值
   this.heightArr = [];
   for(var i=0;i<this.maxNum;i++){
    this.heightArr.push(this.abox[i].offsetHeight);
   }
  }
  otherLine(){
   // 需要拿到後面行的所有元素
   for(var i=this.maxNum;i<this.abox.length;i++){
    var min = getMin(this.heightArr);
    var minIndex = this.heightArr.indexOf(min);
    // 設定定位
    this.abox[i].style.position = "absolute";
    // 根據最小值設定top
    this.abox[i].style.top = min + "px";
    // 根據最小值的索引設定left
    this.abox[i].style.left = minIndex * this.abox[0].offsetWidth + "px";
    // 修改最小值為,原來的資料+當前新放置元素的高度
    this.heightArr[minIndex] = this.heightArr[minIndex] + this.abox[i].offsetHeight;
   }
  }
 }
 function getMin(arr){
  var myarr = [];
  for(var j=0;j<arr.length;j++){
   myarr.push(arr[j]);
  }
  return myarr.sort((a,b)=>a-b)[0];
 }
</script>

效果:

JS實現瀑布流效果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。