在waterfallLayout.html文件里:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /> <title>瀑布流布局</title> <meta name="module-info" content=""> <meta name="author" content="xuld@vip.qq.com"> <meta name="description" content="经典瀑布流布局模型。"> <!-- 以下是本组件的全部源码 --> <!--<script type="text/javascript" src="../../utility/dom/dom.js"></script>--> <script type="text/javascript" src="../../control/layout/waterfallLayout.js"></script> </head> <body> <!-- 以下代码仅用于文档演示 --> <script type="text/javascript" src="../../../assets/doc/doc.js"></script> <style> #waterfallLayout1 > div { background: #f7f7f7; } </style> <div id="waterfallLayout1"> <div style="height:50px;">我是元素1</div> <div style="height:70px;">我是元素2</div> <div style="height:30px;">我是元素3</div> <div style="height:80px;">我是元素4</div> <div style="height:30px;">我是元素5</div> <div style="height:50px;">我是元素6</div> <div style="height:70px;">我是元素7</div> <div style="height:30px;">我是元素8</div> <div style="height:80px;">我是元素9</div> <div style="height:30px;">我是元素10</div> </div> <script class="doc-demo">waterfallLayout(document.getElementById('waterfallLayout1'))</script> </body> </html>
在waterfallLayout.js文件里:
/** * 对指定节点进行瀑布流布局。 * @param {Element} container 要布局的容器。 * @param {Number} [columnCount=4] 要分割的列数。 * @param {Number} [rowSpace=10] 每行之间的空白。 * @param {Number} [columnSpace=10] 每列之间的空白。 */ function waterfallLayout(container, columnCount, rowSpace, columnSpace) { if (columnCount == null) { columnCount = 4; } if (rowSpace == null) { rowSpace = 10; } if (columnSpace == null) { columnSpace = 10; } // 支持内部元素绝对位置。 container.style.position = 'relative'; var node = container.firstElementChild, layoutInfo = [], leftInfo = [], minColumn = 0, i, columnWidth = (container.offsetWidth - columnSpace * (columnCount - 1)) / columnCount; // 初始化每列信息。 for (i = 0; i < columnCount; i++) { layoutInfo[i] = 0; leftInfo[i] = minColumn; minColumn += columnWidth + columnSpace; } // 对每个节点布局。 for (; node; node = node.nextElementSibling) { node.style.position = "absolute"; node.style.width = columnWidth + "px"; minColumn = 0; // 从每一列中找到最小的列。 for (i = 1; i < columnCount; i++) { if (layoutInfo[i] < layoutInfo[minColumn]) { minColumn = i; } } node.style.left = leftInfo[minColumn] + "px"; node.style.top = layoutInfo[minColumn] + "px"; layoutInfo[minColumn] += node.offsetHeight + rowSpace; } // 设置容器的高度。 minColumn = 0; for (i = 0; i < columnCount; i++) { if (layoutInfo[i] > minColumn) { minColumn = layoutInfo[i]; } } container.style.height = Math.max(minColumn - rowSpace, 0) + "px"; }
nextElementSibling:下一个兄弟节点