0

我的网站中有以下 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). 我不确定这是否意味着我需要一个插件,如果需要,那究竟意味着什么。

任何想法和帮助将不胜感激

4

2 回答 2

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)
于 2013-08-08T22:20:11.107 回答
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");
      });
    });
  }
});
于 2013-08-08T22:31:13.177 回答