使我的jQuery更易于重用

时间:2013-08-08 22:12:51

标签: jquery function

我的网站上有以下jQuery代码,用于整理wordpress网站的垂直节奏:

$(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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

尝试类似:

$.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");
      });
    });
  }
});
相关问题