LoginSignup
0
0

More than 5 years have passed since last update.

[Javascript] Masonryのitemの小要素をimgタグにして高さを可変にする方法

Posted at

hoverしてオーバーレイで何か表示したいときなど、⇣のように画像をdivでラップしたDOMの構成にしたい。

<div class="masonry">
  <div class="item">
    <img src="https://placehold.it/200x200" />
  </div>
  <div class="item">
    <img src="https://placehold.it/200x200" />
  </div>
  <div class="item">
    <img src="https://placehold.it/200x200" />
  </div>
</div>

デフォルトの設定だと画像の高さが反映されず、レイアウトが崩れるので、
公式に従うと、imagesloaded を使えば解決できる
https://masonry.desandro.com/layout.html#imagesloaded

jQuery

// init Masonry
var $grid = $('.grid').masonry({
  // options...
});
// layout Masonry after each image loads
$grid.imagesLoaded().progress( function() {
  $grid.masonry('layout');
});

Vanilla JS

// import imagesLoaded anywhere

imagesLoaded(container, function () {
  var msnry = new Masonry(container, {
    columnWidth: 200,
    itemSelector: '.item'
  });
});

react-masonry-component


<Masonry
    className={'my-gallery-class'}
    options={masonryOptions}
    disableImagesLoaded={false} // ここをfalseにする(デフォルト)
    updateOnEachImageLoad={true} // ここをtrueにする(デフォルトはfalse)
>
    {childElements}
</Masonry>
0
0
0

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
0
0