標籤:float ring attr log 網站 需要 from end mos
瀑布流就是像瀑布一樣的網站——豐富的網站內容,特別是絢美的圖片會讓你流連忘返。你在瀏覽網站的時候只需要輕輕滑動一下滑鼠滾輪,一切的美妙的圖片精彩便可呈現在你面前。瀑布流網站是新興的一種網站模式——她的典型代表是pinterest、美麗說、蘑菇街這類型的網站。
下面是效果:
核心內容:
1.先設定布局,主要HTML代碼如下
<div id="container"> <div class="box"> <div class="content"> <img src="../imgs/Girls/01.jpg"> </div> </div> ...</div>
然後設定寬度固定,高度自適應,.box 相對布局,向左浮動:
.box { position: relative; float: left; }.content { padding: 2px; border: 1px solid #ccc; border-radius: 2px; }.content img { width: 234px; height: auto; }#container { background: #fff none repeat scroll 0 0; margin: 0 auto; width: auto; }
2.圖片位置擺放
因為圖片的高度不一致,先根據頁面大小擷取第一行的圖片數量,然後把第二行第一個張圖片放到第一行高度最低的圖片下面,以此類推:
function imgLocation() { var box = $(".box"); var boxWidth = box.eq(0).width(); //擷取第一張圖片的寬度 var num = Math.floor($(window).width()/boxWidth); //確定一排能放多少張圖片 var container = num * boxWidth+"px"; $("#container").css("max-width",container); var boxArr = []; //擷取盒子高度 box.each(function (index, value) { var boxHeight = box.eq(index).height(); if(index < num){ boxArr[index] = boxHeight; }else { var minboxHeight = Math.min.apply(null,boxArr); //擷取最小高度 var minboxIndex = $.inArray(minboxHeight,boxArr); //通過位置進行擺放 $(value).css({ "position":"absolute", "top":minboxHeight, "left":box.eq(minboxIndex).position().left }); //重新計算高度 boxArr[minboxIndex] += box.eq(index).height(); } });}
3.滾動式載入
然後通過判斷滑鼠是否滑動到底部,確定是否自動載入資料。
先判斷是否滑到頁面底部:
function scrollSide() { var box = $(".box"); var lastBoxHeight = box.last().get(0).offsetTop + Math.floor( box.last().height()/2); // 當前頁面的高度 var documentHeight = $(window).height(); // 滑鼠滾動的高度 var scrollHeight = $(window).scrollTop(); return (lastBoxHeight < (scrollHeight + documentHeight))?true:false; //是否允許滾動}
然後監聽滾動事件,當滿足載入條件時,載入圖片:
//監聽滑鼠監聽事件 window.onscroll = function () { //最後一張圖片出現一半時載入 if(scrollSide()){ $.each(dataImg.data,function (index, value) { var box = $("<div>").addClass("box").appendTo($("#container")); var content = $("<div>").addClass("content").appendTo(box); $("<img>").attr("src",$(value).attr("src")).appendTo(content); }); imgLocation(); } };
PS:也可以通過Ajax 初始化圖片HTML 程式碼:
//初始化圖片function initializeImgs() { $.ajax({ type:‘GET‘, url:url4girls, dateType:‘xml‘, success:function (data) { addImgBox(data); } });};function addImgBox(data) { var arr = $(data).find(‘string‘); $.each(arr,function (index, value) { var box = $("<div>").addClass("box").appendTo($("#container")); var content = $("<div>").addClass("content").appendTo(box); $("<img>").attr("src",$(value).text()).appendTo(content); }); imgLocation();}
相關檔案:
index_by_jQuery.htmlindex_by_jQuery.jsindex_by_jQuery_Ajax.htmlindex_by_jQuery_Ajax.jswaterfall.cssjquery-3.1.1.min.js
具體可查看源碼
【jQuery Demo】圖片瀑布流實現