js瀑布流布局

    xiaoxiao2022-07-04  151

    效果

    一行多列显示图片,每一列图片高度不固定,宽度固定,即使第一行图片的高度不同,下一行所有图片和上一行图片的间距相等。

    实现思路

    第一行图片正常排列,第二行绝对定位,第一列的元素left:0,第二列left为每一列的宽度,top值由第二行开始计算,为上一行同列top+上一行图片height。

    待改善

    看到瀑布流的大概效果按着自己思路随便写了一个,怪蠢的,写完之后再看别人的,发现瀑布流下一行第一个元素的排布是在上一行高度最低的那一列

    代码

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> .body{ margin: 0; padding: 0; } .box{ font-size: 0; position: relative; } .box img{ padding-left: 20px; padding-bottom: 20px; clear: both; vertical-align: top; width: 400px; } </style> <body> <div class="box" id="box"> <img src="image/0.jpg" alt="" class="item"> <img src="image/1.jpg" alt="" class="item"> <img src="image/2.jpg" alt="" class="item"> <img src="image/3.jpg" alt="" class="item"> <img src="image/4.jpg" alt="" class="item"> <img src="image/5.jpg" alt="" class="item"> <img src="image/6.jpg" alt="" class="item"> <img src="image/7.jpg" alt="" class="item"> <img src="image/8.jpg" alt="" class="item"> <img src="image/9.jpg" alt="" class="item"> </div> <script> window.onload = function(){ var boxWidth = document.getElementById("box").offsetWidth; var item = document.getElementsByTagName("img"); var itemWidth = item[0].offsetWidth; var cowNum = parseInt (boxWidth / itemWidth); for( var i = cowNum ; i < item.length ; i++ ) { item[i].style.position = "absolute"; item[i].style.left = (i % cowNum) * itemWidth + 'px'; var previousRowItemTop = (document.defaultView.getComputedStyle(item[i-cowNum]).top).slice(0,-2); console.log(previousRowItemTop); if(i<cowNum*2) { item[i].style.top = item[i-cowNum].offsetHeight +'px'; } else { item[i].style.top = parseInt(previousRowItemTop) + item[i-cowNum].offsetHeight +'px'; } } } </script> </body> </html>
    最新回复(0)