LoginSignup
11

More than 3 years have passed since last update.

jquery.tile.jsをRails + CoffeeScriptで使用する方法

Last updated at Posted at 2016-01-26

image
※公式サイトより拝借
http://urin.github.io/jquery.tile.js/

こんな感じで、やっべえー要素がズレこんじゃったよーって言う時、ありませんか?

そんな時に、jquery.tile.jsを使用すると、楽に要素の高さを揃えることができます。

image

こんな感じに :smile:

jquery.tile.jsとは

jquery.tile.jsは、要素の高さをあわせるjqueryプラグインの中でも最軽量のものです。(jquery.tile.js開発者調べ)

image
https://github.com/urin/jquery.tile.js

それでは、railsの中で実装してみましょう

lib/assets/javascriptにjquery.tile.jsを作成します。

(function($) {
  $.fn.tile = function(columns) {
    var tiles, $tile, max, c, h, remove, s = document.body.style, a = ["height"],
      last = this.length - 1;
    if(!columns) columns = this.length;
    remove = s.removeProperty ? s.removeProperty : s.removeAttribute;
    return this.each(function() {
      remove.apply(this.style, a);
    }).each(function(i) {
      c = i % columns;
      if(c == 0) tiles = [];
      $tile = tiles[c] = $(this);
      h = ($tile.css("box-sizing") == "border-box") ? $tile.outerHeight() : $tile.innerHeight();
      if(c == 0 || h > max) max = h;
      if(i == last || c == columns - 1) {
        $.each(tiles, function() { this.css("height", max); });
      }
    });
  };
})(jQuery);

次に、app/assets/javascript/任意.coffeeを作成します

$ ->
  $('任意のクラス名').tile()

これで終わりです。ただ、これだとすべての要素の高さが揃ってしまうので、列ごとに高さを分けたい場合は....

例えば、列が3列の場合

$ ->
  $('任意のクラス名').tile(3)

というふうにしてみてください。

SpecialThanks

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11