2013-08-08 2 views
0

У меня есть следующий JQuery код в свой веб-сайт для сортировки вертикальный ритм моего сайта WordPress:сделать мой JQuery более многоразовый

$(window).bind('load', function(){ 
     $(".wp-caption").each(function() { 
       /* variables */ 
       var this_img = $(this); 
       var baseline = 24; 
       var img_height = this_img.outerHeight(); 
      /* do the maths */ 
      var remainder = parseFloat(img_height%baseline); 

      /* how much do we need to add? */ 
      var offset  = parseFloat(baseline-remainder); 

      var top_offset = Math.round(offset/2); 
      var bottom_offset = offset - top_offset; 

      /* apply the margin to the image */ 
      this_img.css("margin-bottom",bottom_offset+"px"); 
      this_img.css("margin-top",top_offset+"px"); 
     }); 
}); 

Я хотел бы сделать это более пригодными для повторного использования, так что вместо заполнения всего кода в .bind Я могу сделать что-то вроде $(".wp-caption").verticalRhythm(24). Я не уверен, что это означает, что мне нужен плагин, и если да, то что именно это означает.

Любые идеи и помощь был бы оценен

ответ

2

Да, это то, как плагин. Вот в основном то, что это будет выглядеть как:

(function($) { 

$.fn.verticalRhythm = function(baseline) { 
    return this.each(function() { 
     var this_img = $(this); 
     var img_height = this_img.outerHeight(); 
     /* do the maths */ 
     var remainder = parseFloat(img_height%baseline); 

     /* how much do we need to add? */ 
     var offset  = parseFloat(baseline-remainder); 

     var top_offset = Math.round(offset/2); 
     var bottom_offset = offset - top_offset; 

     /* apply the margin to the image */ 
     // this_img.css("margin-bottom",bottom_offset+"px"); 
     // this_img.css("margin-top",top_offset+"px"); 
     // jQuery will add pixels to css values. And you add them all at once. 
     this_img.css({ marginTop: top_offset, marginBottom: bottom_offset }); 
    }); 
}; 

})(jQuery) 
+0

При сравнении это ответ @PHPglue «s, существует ряд различий - что оберточная' (функция ($) {'и'}) (jQuery) 'about? – Jamie

+1

Это называется [Выражение выраженной функции (IIFE)] (http://benalman.com/news/2010/11/immediately-invoked-function-expression/). Он инкапсулирует весь код, а также удостоверяет, что '$' равно 'jQuery', даже если пользователь использует' jQuery.noConflict'. – kalley

0

Try что-то вроде:

$.fn.extend({ 
    verticalRhythm : function(baseline){ 
    $(window).bind('load', function(){ 
     $(this).each(function(){ 
     var this_img = $(this), img_height = this_img.outerHeight(); 
     var remainder = parseFloat(img_height%baseline); 
     var offset = parseFloat(baseline-remainder); 
     var top_offset = Math.round(offset/2); 
     var bottom_offset = offset - top_offset; 
     this_img.css("margin-bottom",bottom_offset+"px"); 
     this_img.css("margin-top",top_offset+"px"); 
     }); 
    }); 
    } 
}); 
Смежные вопросы