原生js實現(xiàn)瀑布流效果
更新時間:2020年03月09日 10:20:29 作者:Tangerine.
這篇文章主要為大家詳細介紹了原生js實現(xiàn)簡單瀑布流效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了js實現(xiàn)瀑布流效果的具體代碼,供大家參考,具體內(nèi)容如下
CSS樣式:
<style>
.cont{margin: 0 auto;position: relative;}
.box{float: left;padding: 5px;}
.imgbox{border: black solid 1px;padding: 5px;border-radius: 5px;}
.imgbox img{width: 200px;display: block;}
</style>
HTML結(jié)構(gòu):
<div class="cont"> <div class="box"> <div class="imgbox"> <img src="img/1.jpg" > </div> </div> //......此處省略雷同代碼 <div class="box"> <div class="imgbox"> <img src="img/2.jpg" > </div> </div> </div>
JavaScript代碼:
<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 = Math.min(...this.heightArr);
var minIndex = this.heightArr.indexOf(min);
this.abox[i].style.position = "absolute";
this.abox[i].style.top = min + "px";
this.abox[i].style.left = minIndex * this.abox[0].offsetWidth + "px";
this.heightArr[minIndex] = this.heightArr[minIndex] + this.abox[i].offsetHeight;
}
}
}
</script>
小編還為大家準備了精彩的專題:瀑布流布局匯總
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript中的await函數(shù)使用小結(jié)
async 函數(shù)是 AsyncFunction 構(gòu)造函數(shù)的實例,并且其中允許使用 await 關(guān)鍵字,async 和 await 關(guān)鍵字讓我們可以用一種更簡潔的方式寫出基于 Promise 的異步行為,而無需刻意地鏈式調(diào)用 promise,這篇文章主要介紹了JavaScript中的await,需要的朋友可以參考下2024-01-01
深度剖析JavaScript作用域從局部到全局一網(wǎng)打盡
這篇文章主要為大家介紹了JavaScript作用域的深度剖析,從局部到全局一網(wǎng)打盡,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
頁面縮放兼容性處理方法(zoom,Firefox火狐瀏覽器)
下面小編就為大家?guī)硪黄撁婵s放兼容性處理方法(zoom,Firefox火狐瀏覽器)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08

