系統城裝機大師 - 唯一官網:www.farandoo.com!

當前位置:首頁 > 網絡編程 > JavaScript > 詳細頁面

JS實現瀑布流效果

時間:2020-03-07來源:電腦系統城作者:電腦系統城

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

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

CSS部分:


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

HTML部分(圖片可自行添加):


 
  1. <div class="cont">
  2. <div class="box">
  3. <div class="imgbox">
  4. <img src="../img/WaterF2.jpg" alt="JS實現瀑布流效果">
  5. </div>
  6. </div>
  7. <div class="box">
  8. <div class="imgbox">
  9. <img src="../img/WaterF1.jpg" alt="JS實現瀑布流效果">
  10. </div>
  11. </div>
  12. // ...
  13. </div>

JS部分:


 
  1. <script>
  2. onload = function(){
  3. var wf = new WaterF();
  4. wf.init();
  5. }
  6. class WaterF{
  7. constructor(){
  8. this.clientW = document.documentElement.clientWidth;
  9. this.abox = document.querySelectorAll(".box");
  10. this.cont = document.querySelector(".cont");
  11. }
  12. init(){
  13. // 根據屏幕的寬度 / 任意一個結構的寬度,得到一行最多能放多少個圖片
  14. this.maxNum = parseInt(this.clientW / this.abox[0].offsetWidth);
  15. // 根據一行能放置的個數 * 任意一張圖片的寬度,得到了外框的真正的寬度
  16. this.cont.style.width = this.maxNum * this.abox[0].offsetWidth + "px";
  17. // 完善布局之后,開始區分第一行和后面的行
  18. this.firstLine();
  19. this.otherLine();
  20. }
  21. firstLine(){
  22. // 第一行,獲取所有元素的高度放在一個數組中,準備獲取最小值
  23. this.heightArr = [];
  24. for(var i=0;i<this.maxNum;i++){
  25. this.heightArr.push(this.abox[i].offsetHeight);
  26. }
  27. }
  28. otherLine(){
  29. // 需要拿到后面行的所有元素
  30. for(var i=this.maxNum;i<this.abox.length;i++){
  31. var min = getMin(this.heightArr);
  32. var minIndex = this.heightArr.indexOf(min);
  33. // 設置定位
  34. this.abox[i].style.position = "absolute";
  35. // 根據最小值設置top
  36. this.abox[i].style.top = min + "px";
  37. // 根據最小值的索引設置left
  38. this.abox[i].style.left = minIndex * this.abox[0].offsetWidth + "px";
  39. // 修改最小值為,原來的數據+當前新放置元素的高度
  40. this.heightArr[minIndex] = this.heightArr[minIndex] + this.abox[i].offsetHeight;
  41. }
  42. }
  43. }
  44. function getMin(arr){
  45. var myarr = [];
  46. for(var j=0;j<arr.length;j++){
  47. myarr.push(arr[j]);
  48. }
  49. return myarr.sort((a,b)=>a-b)[0];
  50. }
  51. </script>

效果:

JS實現瀑布流效果

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

分享到:

相關信息

系統教程欄目

欄目熱門教程

人氣教程排行

站長推薦

熱門系統下載

jlzzjlzz亚洲乱熟在线播放