代码之家  ›  专栏  ›  技术社区  ›  DanyNsg

带网格布局的砌体廊道

  •  2
  • DanyNsg  · 技术社区  · 8 年前

    我一直在寻找一个有网格布局的砖石画廊,我没有找到,所以我决定自己做。我在网格布局中使用customElement,但在动态分配网格行时会被阻止。
    我希望得到您的反馈并帮助改进。

    • 需要运行2次才能工作

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

    小提琴 https://jsfiddle.net/znhybgb6/6/

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ilya Streltsyn    8 年前

    您的“bug”有以下原因:

    1. 网格行之间有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)
    
        })
    
      }
    

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

    in the edited Fiddle