Masonry系の最強スクリプト、レスポンシブ対応のレイアウトが簡単に実装できる -Muuri
Post on:2016年12月22日
カードやパネルをレンガ状に配置し、ドラッグして配置をアニメーションで変更、ソートやフィルタリング機能も可能なグリッドレイアウトが簡単に実装できるスクリプトを紹介します。
マウスで操作しても、タッチデバイスで操作しても、非常に快適です。

Muuriのデモ
デモはモダンブラウザ、IE9+でご覧ください。スマホやタブレットでも動作します。
※スマホだと各パネルが大きいので、操作しにくいかも。

各パネルをドラッグすると、アニメーションで配置を変更するだけでなく、ソートやフィルタリング機能も備わっています。

機能は上部のセレクトフォーム
カラーでソートしてみました。

ソート機能: カラー
面白い機能として、レイアウト方法を変更することもできます。

通常は左・上を基準にパネルを順番に配置しますが、隙間がでないことを優先にさせたり、右や下を基準にすることもできます。

右・下を基準に配置
Muuriの使い方
Step 1: 外部ファイル
当スクリプトとVelocityとHamemr.jsの3つを外部ファイルとして記述します。
1 2 3 4 5 6 7 8 |
<body> ... コンテンツ ... <script src="velocity.js"></script> <script src="hammer.js"></script> <script src="muuri.js"></script> </body> |
Step 2: HTML
グリッドはdiv要素で実装し、1つのグリッドに対して最低2つ以上のアイテムが必要です。アイテムが入れ子になっているのは、外側はアイテムを配置するため、内側はアニメーションのため、となっています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<div class="grid"> <div class="item"> <div class="item-content"> This can be anything. </div> </div> <div class="item"> <div class="item-content"> <div class="my-custom-content"> Yippee! </div> </div> </div> </div> |
Step 3: CSS
グリッドを構成する基本となるスタイルシートです。
基本的には変更する必要はありませんが、各パネルの隙間を調整したい場合は.itemのmargin値を変更します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
.grid { position: relative; } .item { display: block; position: absolute; width: 100px; height: 100px; margin: 5px; z-index: 1; } .item.muuri-dragging, .item.muuri-releasing { z-index: 2; } .item.muuri-hidden { z-index: 0; } .item-content { position: relative; width: 100%; height: 100%; } |
Step 4: JavaScript
最後に、スクリプトを初期化して実行します。
1 2 3 4 |
var grid = new Muuri({ container: document.getElementsByClassName('grid')[0], items: document.getElementsByClassName('item') }); |
オプションなど、さらに詳しい情報は下記をご覧ください。
sponsors