【发布时间】:2017-08-21 17:18:45
【问题描述】:
我一直在寻找一个网格布局的 Masonry 画廊,但我没有找到它,所以我决定自己做。我使用带有网格布局的 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)
【问题讨论】:
-
您查看文档了吗? isotope.metafizzy.co/layout-modes/masonry.html 有很多例子。做一个画廊布局就是它的作用。
-
请检查您的小提琴的以下分支:jsfiddle.net/znhybgb6/12。主要变化:加载后计算图像高度,100px 高的自动网格行,在计算中考虑间隙高度。
标签: javascript css grid-layout css-grid