| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

JQuery プラグインの作成

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

jQuery プラグインの作成

jQuery | JavaScript |

骨格

  • プラグインを匿名関数でラップし、すぐその関数を実行することで、$ でjQueryオブジェクトを参照できる (1)
  • jQuery.fn オブジェクトをメソッド名で拡張しjQueryメソッドを作成する (2)
  • jQuery オブジェクトは複数の結果に対応する必要があるので、each() 処理を行う (3)
;(function($){    // (1) 
  $.fn.lightable = function(options) { // (2)
    var options = $.extend({
      // デフォルトのオプション
    },options);
    
    return this.each(function(){ // (3)
      // 処理本体
      
    });
  };
})(jQuery);

作成例

;(function($){
  $.fn.lightable = function(options) {
    var cfg = $.extend({
      height:"100%",
    },options);
    
    var table, headerTable;
    var wrapper, headWrapper, bodyWrapper;
    
    /**
     * 処理本体
     */
    return this.each(function(){
      table = $(this);
      table.attr({cellspacing:"0", border:"0", cellpadding:"0" });
      
      headerTable = $(document.createElement("table"));
      headerTable.attr({cellspacing:"0", border:"0", cellpadding:"0" });
      
      headerTable.prepend($("thead", table).addClass("ui-widget-header").clone());
      $('thead tr',headerTable).append("<th></th>");  // for scrollbar
      
      // 固定レイアウトアルゴリズムを利用するように属性を設定(table-layout=fixed かつ widthプロパティが指定される必要がある)
      var tattr = {"table-layout":"fixed", "width":"100%"};
      table.css(tattr);
      headerTable.css(tattr);
      
      if (cfg.cols) {
        var cg = new Array();
        $(cfg.cols).each(function(){
          cg.push("<col");
          if ("width" in this) {
            cg.push(" width='");
            cg.push(this.width);
            cg.push("'");
          }
          cg.push("/>");
        });
        table.prepend(cg.join(""));
        
        // for scrollbar
        cg.push("<col width='18px'/>");
        headerTable.prepend(cg.join(""));
      }
      
      // 構造を作成
      table.wrapAll("<div class='lightable-wrapper' style='width:100%;'>"
              + "<div class='lightable-body-wrapper' style='overflow:auto;width:100%;"
              + "height:" + cfg.height + ";'></div></div>");

      wrapper = table.closest(".lightable-wrapper");
      wrapper.prepend("<div class='lighttable-head-wrapper' style='overflow:hidden;width:100%;height:100%;'></div>");
      
      headWrapper = $(".lighttable-head-wrapper", wrapper); 
      bodyWrapper = table.closest(".lightable-body-wrapper");
      headWrapper.prepend(headerTable);
      
      $("thead" ,table).hide();
      
      bodyWrapper.scroll(function(){
        headWrapper.scrollLeft(this.scrollLeft);
      });
    });
  };
})(jQuery);