瀑布流简单实现
瀑布流画册,主要是要求出列数,超出列数的图片,按照顺序,每次找到高度最小的一列,进行排列
<div> <div class="item"><img src="https://avatars.githubusercontent.com/u/11458263?s=80&u=8abd594f236f381da9cbe70bade832663ecb4bd0&v=4"></div> <div class="item"><img src="https://static.jsbin.com/images/dave.min.svg"></div> <div class="item"><img src="https://images.unsplash.com/photo-1679068476679-5057c5c5d256?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt=""></div> <div class="item"><img src="https://images.unsplash.com/photo-1679068476679-5057c5c5d256?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60" alt=""></div> <div class="item"><img src="https://static.jsbin.com/images/dave.min.svg"></div> <div class="item"><img src="https://avatars.githubusercontent.com/u/11458263?s=80&u=8abd594f236f381da9cbe70bade832663ecb4bd0&v=4"></div> <div class="item"><img src="https://avatars.githubusercontent.com/u/11458263?s=80&u=8abd594f236f381da9cbe70bade832663ecb4bd0&v=4"></div> <div class="item"><img src="https://avatars.githubusercontent.com/u/11458263?s=80&u=8abd594f236f381da9cbe70bade832663ecb4bd0&v=4"></div> <div class="item"><img src="https://avatars.githubusercontent.com/u/11458263?s=80&u=8abd594f236f381da9cbe70bade832663ecb4bd0&v=4"></div> <div class="item"><img src="https://avatars.githubusercontent.com/u/11458263?s=80&u=8abd594f236f381da9cbe70bade832663ecb4bd0&v=4"></div> <div class="item"><img src="https://avatars.githubusercontent.com/u/11458263?s=80&u=8abd594f236f381da9cbe70bade832663ecb4bd0&v=4"></div> <div class="item"><img src="https://avatars.githubusercontent.com/u/11458263?s=80&u=8abd594f236f381da9cbe70bade832663ecb4bd0&v=4"></div> </div>
#waterfall { width: 100%; margin: 0 auto; } .item { width: 30%; margin: 10px; float: left; overflow: hidden; } .item img { width: 100%; height: auto; }
window.onload = function() { var waterfall = document.getElementById("waterfall"); var items = waterfall.getElementsByClassName("item"); var gap = 10; var itemWidth = items[0].offsetWidth + gap; var columns = Math.floor(waterfall.offsetWidth / itemWidth); var heights = []; for (var i = 0; i < items.length; i++) { if (i < columns) { heights.push(items[i].offsetHeight); } else { var minHeight = Math.min.apply(null, heights); var minIndex = heights.indexOf(minHeight); items[i].style.position = "absolute"; items[i].style.top = minHeight + "px"; items[i].style.left = minIndex * itemWidth + "px"; heights[minIndex] += items[i].offsetHeight + gap; } } };
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论