网格布局的砌体画廊

丹妮

我一直在寻找具有网格布局的砌体画廊,但没有找到它,所以我决定自己动手做。我使用带有网格布局的customElement,但是在动态分配网格行时会被阻塞。
我希望收到您的反馈,并帮助改善它。

我检测到的一些错误是:

  • 需要运行2次才能正常工作
  • 图像/容器高度不是100的倍数时的空白

的HTML

<masonry-gallery></masonry-gallery>

JS

 class MasonryGallery extends HTMLElement {

    items = [
    { image:'https://unsplash.it/200/100/' },
    { image:'https://unsplash.it/200/200/' },
    { image:'https://unsplash.it/200/300/' },
    { image:'https://unsplash.it/200/400/' },
    { image:'https://unsplash.it/200/300/' },
    { image:'https://unsplash.it/200/200/' },
    { image:'https://unsplash.it/200/100/' },
    { image:'https://unsplash.it/200/300/' },
    { image:'https://unsplash.it/200/700/' },
    { image:'https://unsplash.it/200/300/' },
    { image:'https://unsplash.it/200/200/' },
    { image:'https://unsplash.it/200/600/' },
    { image:'https://unsplash.it/200/100/' }
  ]

  constructor() {
    super()
    this.attachShadow({ mode: 'open'})
    this.create()
    this.append()
  }

  create() {
    this.style.display = 'grid'
    this.style.gridTemplateColumns = 'repeat(auto-fill, 200px)'
    this.style.gridTemplateRows = 'repeat(auto-fill, 1fr)'
    this.style.gridGap = '1rem'
    this.style.gridAutoFlow = 'row dense'
  }

  append() {

    this.items.map(item => {

        const div = document.createElement('DIV');
      const image = document.createElement('IMG')

      image.src = item.image
      div.appendChild(image)

      this.shadowRoot.appendChild(div)

      div.style.gridRow = 'auto / span ' + [...String(image.height)][0]
    })

  }

}

customElements.define('masonry-gallery', MasonryGallery)

FIDDLE https://jsfiddle.net/znhybgb6/6/

伊利亚(Ilya Streltsyn)

您的“错误”有以下原因:

  1. 您尝试在将图像附加到组件之后立即计算图像的高度,但是此时它的高度是未知的,只有在图像加载后才能知道。
  2. 网格行之间有1rem(16px)的间隙,因此每张100px高的图像会增加116px的网格高度。

可以通过以下append方法来解决此问题:

append() {

    let gap = parseInt(getComputedStyle(this).gridRowGap)

    this.items.map(item => {

        const div = document.createElement('DIV');
      const image = document.createElement('IMG')
      image.style.display = 'block';

      image.src = item.image
      div.appendChild(image)
      image.onload = function() {
          this.parentNode.style.gridRow = 'auto / span ' + ((this.height + gap)/(100 + gap));
      }

      this.shadowRoot.appendChild(div)

    })

  }

和更换gridRowsgridAutoRows = '100px'用于使垂直节奏均匀,并相应地调整图像的高度。

您可以在编辑的Fiddle中查看结果

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章