佈局的原理: 用一個類名爲item的div做爲圖片的容器,每一個item的寬都相等,高度自適應,使用絕對定位。第一行的item只須要處理left就不詳細說了。第二行之後:獲取到第一行的item的高度做爲這一列的高度,找到其中最小的值,那麼從第二行開始的item的top值就等於這個值,而left就等於這一列的left,這個時候這一列的高度+=當前處理的item的高度。css
附上詳細代碼html
HTML部分:jquery
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <div id="picturewall"></div> </body> </html>
CSS:web
*{ font-family: "microsoft yahei",sans-serif; padding: 0; margin: 0; } #picturewall{ width: 940px; height: auto; margin: 0 auto; position: relative; } .item{ width: 300px; height: auto; box-sizing: border-box; border: 1px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 0 15px #666; -moz-box-shadow: 0 0 15px #666; box-shadow: 0 0 15px #666; position: absolute; text-align: center; } .item>img{ height: auto; width: 280px; display: block; margin: 10px; }
jquery :ajax
$(function(){ //用數組存放圖片的文件名 var pictureSources = [ "31bbb105bf1ce318ffd72de5fd601614edda4cd61d278-IjoIRf_fw658.jpg", "57a70575f8a78ffe9d65297e0f75be89a61f14fa3988b2-LgCVaH_fw658.jpg", "6182b15541cb11f6de40ccd9be7239861ba946de26304a-p6giW6_fw658.jpg", "6c0898eb4b898db935c27f8c3319d54b34104e8b22fd8-oKLgCV_fw658.jpg", "9d5992e5231864f09748b6d5f7b03165821bdb4bffc3e-0n27FJ_fw658.jpg", "a1c7f703728f99e7e59fd8c9c250ef8536fa8ae0327fd7-Uh635n_fw658.jpg", "c627789a24da25b438a3d86310e97612f697316bd970-YXUyG9_fw658.jpg", "d7e78fc59a0c102c282a154177ed730295634a241d907-ELAB1U_fw658.jpg", "dcc0754632a597e2ab91ce85eabca8fa71842ac71647e-2pRt4q_fw658.jpg" ]; var base = "picture\/"; //item 元素的基本結構 var baseElem = $("<div class='item'></div>").append("<img/>").append("<hr/>").append("<h4>description</h4>"); //實現瀑布流佈局的函數 function waterfall(){ var items = $("div.item");//獲取到全部的類名爲item的元素 var postop = [];//這個數組用來存放item定位的高度 var itemWidth = items.eq(0).width()+10;//寬度都是同樣的全部隨便獲取一個就行 items.each(function(index,elem){ var targetItemTop = items.eq(index).height()+10;//遍歷全部item並獲取高度 if(index < 3){//若是是在第一行 postop[index] = targetItemTop;//把高度直接加入數組中 $(elem).css({ "left":310*index,//設置left "top": 10//和top }); }else{ //其餘行 var mintop = Math.min.apply(null,postop);//獲取數組中最小的一個 var minindex = $.inArray(mintop,postop);//獲取到數組最小值對應的排序 $(elem).css({ "top":mintop+10,//設置top爲數組中最小值 "left":parseInt(items.eq(minindex).css("left"))//設置left }); } postop[minindex] += $(elem).height()+10;//更新數組 }); } //添加item的函數 function getItems(){ for(var i = 0; i < pictureSources.length; i++){ baseElem.clone().hide().children("img").attr("src",base+pictureSources[i]).bind("load",function(){ waterfall(); $(this).parent().fadeIn(500); }).end().appendTo("#picturewall"); } } //判斷文檔滾動的位置 function wheelListen(){ var srollHeight = $(document).scrollTop(); if(srollHeight+$(window).height() >= $(document).height()-100){ getItems(); } } //綁定事件 $(window).on("load",function(){ getItems(); $(document).bind("mousewheel DOMMouseScroll",function(){ wheelListen(); }); }) });
效果圖:數組
經過滾動鼠標滾輪能夠實現圖片無限加載,配合上ajax基本上就完成了。app