js瀑布流(定位法)
2016-12-21 21:56 muamaker 阅读(443) 评论(0) 编辑 收藏 举报1、首先,自己写好图片路径,引入jquery
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> * { padding: 0; margin: 0; } ul { position: relative; width: 860px; margin: 0 auto; border: 1px solid yellowgreen; } li { width: 200px; position: absolute; list-style: none; } img { width: 100%; border-radius: 8px; } </style> </head> <body> <ul> <li><img src="img/1.jpg" /></li> <li><img src="img/2.jpg" /></li> <li><img src="img/3.jpg" /></li> <li><img src="img/4.jpg" /></li> <li><img src="img/5.jpg" /></li> <li><img src="img/6.jpg" /></li> <li><img src="img/7.jpg" /></li> <li><img src="img/8.jpg" /></li> <li><img src="img/9.jpg" /></li> <li><img src="img/10.jpg" /></li> <li><img src="img/2.jpg" /></li> <li><img src="img/3.jpg" /></li> <li><img src="img/4.jpg" /></li> <li><img src="img/5.jpg" /></li> <li><img src="img/6.jpg" /></li> <li><img src="img/7.jpg" /></li> </ul> </body> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(function() { lazyLoad("ul", "li", 4, 20, 40).init(); /* wrap:外层的dom box:瀑布流的dom clonum:列数 ,默认为3行 marginLeft:每列,间隔,默认为20 marginBottom:每行的间隔,默认为20 startLeft:控制最左边的起始位置,默认不传为0 * */ function lazyLoad(wrap, box, clonum, marginLeft, marginBottom,startLeft) { var posArr = []; var boxList = $(wrap).find(box), boxWidth = boxList.width(); clonum = clonum || 3; marginLeft = marginLeft || 20; marginBottom = marginBottom || 20; startLeft = startLeft || 0; var fn = {}; fn.init = function() { for(var i = 0; i < clonum; i++) { posArr.push({ "top": 0, "left": boxWidth * i + marginLeft * i + startLeft }); } fn.layout(); }; fn.layout = function() { var min = 0, max = 0; boxList.each(function(index, ele) { min = fn.getHeight().minIndex; $(ele).css({ "top": posArr[min].top, "left": posArr[min].left }); posArr[min].top = posArr[min].top * 1 + $(ele).height() * 1 + marginBottom; max = fn.getHeight().maxIndex; /*更新外层的高度*/ $(wrap).css({ "height": posArr[max].top }); }); }; fn.getHeight = function() { var minHeight = posArr[0].top, maxHeight = posArr[0].top, minIndex = 0, maxIndex = 0; for(var i = 0; i < posArr.length; i++) { if(minHeight > posArr[i].top) { minHeight = posArr[i].top; minIndex = i; } if(maxHeight < posArr[i].top) { maxHeight = posArr[i].top; maxIndex = i; } } return { "minIndex": minIndex, "maxIndex": maxIndex }; }; return fn; } }); </script> </html>