gridify.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* ´úÂëÕûÀí£º´óÍ·Íø www.datouwang.com */
  2. 'use strict';
  3. var gridifynrender = null;
  4. (function (factory) {
  5. if (typeof define === 'function' && define.amd) {
  6. define(['jquery'], factory);
  7. } else {
  8. factory(jQuery);
  9. }
  10. }(function ($) {
  11. $.fn.extend({
  12. imagesLoaded: function(cb)
  13. {
  14. var images = $(this).find('img');
  15. var count = images.length;
  16. if (count == 0) cb();
  17. for(var i = 0, length = images.length; i< length; i++)
  18. {
  19. var image = new Image();
  20. image.onload = image.onerror = function(e){
  21. count --;
  22. if (count == 0) cb()
  23. }
  24. image.src = images[i].src;
  25. }
  26. },
  27. gridify: function(options) {
  28. var $this = $(this),
  29. options = options || {},
  30. indexOfSmallest = function (a) {
  31. var lowest = 0;
  32. for (var i = 1, length = a.length; i < length; i++) {
  33. if (a[i] < a[lowest]) lowest = i;
  34. }
  35. return lowest;
  36. },
  37. render = function()
  38. {
  39. $this.css('position', 'relative');
  40. var items = $this.find(options.srcNode),
  41. transition = (options.transition || 'all 0.5s ease') + ', height 0, width 0',
  42. width = $this.innerWidth(),
  43. item_margin = parseInt(options.margin || 0),
  44. item_width = parseInt(options.max_width || options.width || 220),
  45. column_count = Math.max(Math.floor(width/(item_width + item_margin)),1),
  46. left = column_count == 1 ? item_margin/2 : (width % (item_width + item_margin)) / 2,
  47. columns = [];
  48. if (options.max_width) {
  49. column_count = Math.ceil(width/(item_width + item_margin));
  50. item_width = (width - column_count * item_margin - item_margin)/column_count;
  51. left = item_margin/2;
  52. }
  53. for (var i = 0; i < column_count; i++) {
  54. columns.push(0);
  55. }
  56. for(var i = 0, length = items.length; i< length; i++)
  57. {
  58. var $item = $(items[i]), idx = indexOfSmallest(columns);
  59. $item.css({
  60. width: item_width,
  61. position: 'absolute',
  62. margin: item_margin/2,
  63. top: columns[idx] + item_margin/2,
  64. left: (item_width + item_margin) * idx + left,
  65. transition: transition
  66. });
  67. columns[idx] += $item.innerHeight() + item_margin;
  68. if(i == items.length-1){
  69. columns.sort(function (a, b) {
  70. return a-b;
  71. });
  72. $this.css('height', columns[columns.length-1] + item_margin/2);
  73. }
  74. }
  75. };
  76. $this.imagesLoaded(render);
  77. if (options.resizable) {
  78. var resize = $(window).bind("resize", function(){
  79. clearTimeout(gridifynrender);
  80. gridifynrender = setTimeout(render,500);
  81. });
  82. $this.on('remove', resize.unbind);
  83. }
  84. }
  85. });
  86. }));