JS實(shí)現(xiàn)瀑布流效果
本文實(shí)例為大家分享了JS實(shí)現(xiàn)瀑布流效果的具體代碼,供大家參考,具體內(nèi)容如下
話不多說(shuō),直接上代碼。如下:
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='http://www.lshqa.cn/img/WaterF2.jpg' alt=''> </div> </div> <div class='box'> <div class='imgbox'> <img src='http://www.lshqa.cn/img/WaterF1.jpg' alt=''> </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(){ // 根據(jù)屏幕的寬度 / 任意一個(gè)結(jié)構(gòu)的寬度,得到一行最多能放多少個(gè)圖片 this.maxNum = parseInt(this.clientW / this.abox[0].offsetWidth); // 根據(jù)一行能放置的個(gè)數(shù) * 任意一張圖片的寬度,得到了外框的真正的寬度 this.cont.style.width = this.maxNum * this.abox[0].offsetWidth + 'px'; // 完善布局之后,開(kāi)始區(qū)分第一行和后面的行 this.firstLine(); this.otherLine(); } firstLine(){ // 第一行,獲取所有元素的高度放在一個(gè)數(shù)組中,準(zhǔn)備獲取最小值 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); // 設(shè)置定位 this.abox[i].style.position = 'absolute'; // 根據(jù)最小值設(shè)置top this.abox[i].style.top = min + 'px'; // 根據(jù)最小值的索引設(shè)置left this.abox[i].style.left = minIndex * this.abox[0].offsetWidth + 'px'; // 修改最小值為,原來(lái)的數(shù)據(jù)+當(dāng)前新放置元素的高度 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>
效果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 詳解JSP 內(nèi)置對(duì)象request常見(jiàn)用法2. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案3. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介4. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)5. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))6. 詳解盒子端CSS動(dòng)畫性能提升7. ASP實(shí)現(xiàn)加法驗(yàn)證碼8. PHP循環(huán)與分支知識(shí)點(diǎn)梳理9. ASP基礎(chǔ)知識(shí)Command對(duì)象講解10. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法
