瀑布流布局是網(wǎng)頁中經(jīng)常采用的一種布局方式,其布局有如下特點(diǎn):
瀑布流布局特點(diǎn):
(1)圖文元素按列排放
(2)列寬一致,但高度不等
(3)布局過程中將優(yōu)先向高度最小的列補(bǔ)充數(shù)據(jù)
以下是自定義的一個jQuery瀑布流插件:jquery.myWaterfull.js
(function ($) { $.fn.extend({ myWaterfull: function () { var parentWidth = $(this).width(); //獲取每行的寬度 var childItems = $(this).children(); var childWidth = childItems.width(); //獲取每一列的列寬 var column = 5; //定義每行有多少列 //計(jì)算并設(shè)置列與列之間的間隙 var space = (parentWidth - column * childWidth) / (column - 1); //聲明一個數(shù)組,用來存放第一行中每一列的高度 var arrHeight = []; //對子元素進(jìn)行排列布局 $.each(childItems, function (index, item) { if (index < column) { //對第一行的列進(jìn)行排列布局 $(item).css({ top: 0, left: index * (childWidth + space) }); arrHeight.push($(item).height() + space); //將第一行中的列的高度添加到數(shù)組中 } else { //找尋列高最小的那一列 var minIndex = 0; var minValue = arrHeight[minIndex]; //循環(huán)遍歷找出最小的列高值 for (var i = 0; i < arrHeight.length; i++) { if (minValue > arrHeight[i]) { minValue = arrHeight[i]; minIndex = i; } } //對余下的子元素挨個排列布局 $(item).css({ top: minValue + space, left: minIndex * (childWidth + space) }); //更新最小列高 arrHeight[minIndex] += $(item).height() + space; } }); //由于這里是利用定位對子元素進(jìn)行布局,所以要更新父元素的高度 //當(dāng)然也可以利用浮動對子元素進(jìn)行布局 var maxHeight = 0; for (var i = 0; i < arrHeight.length; i++) { if (maxHeight < arrHeight[i]) { maxHeight = arrHeight[i]; } } //設(shè)置父元素的高度 $(this).height(maxHeight); } });})(jQuery);使用示例:
這里假設(shè)一個HTML結(jié)構(gòu):
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <title>瀑布流案例原始</title> <style>* { margin: 0; padding: 0;}body { font-family: Microsoft Yahei; background-color: #f5f5f5;}.container { width: 1200px; margin: 0 auto; padding-top: 50px;}.container > .items { position: relative;}.container > .items > .item { width: 232px; position: absolute; box-shadow: 0 1px 3px rgba(0, 0, 0, .3); overflow: hidden;}.container > .items > .item > img { width: 100%; display: block; height: 232px;}.container > .items > .item:nth-child(3n) > img { width: 100%; display: block; height: 350px;}.container > .items > .item > p { margin: 0; padding: 10px; background: #fff;}.container > .btn { width: 280px; height: 40px; text-align: center; line-height: 40px; background-color: #ccc; border-radius: 8px; font-size: 24px; cursor: pointer;}.container > .loading { background-color: transparent;}</style></head><body><div class="container"> <div class="items"> </div> <div class="btn loading">正在加載...</div></div>
新聞熱點(diǎn)
疑難解答
圖片精選