小程序瀑布流布局样式算法

const calMasonryPhotoList = (data, cols, gap) => {

    const cols = 4
    const gap = 8

    const { screenWidth, pixelRatio } = wx.getSystemInfoSync()

    const imgWidth = Math.floor((screenWidth - gap * 2 - gap * (cols - 1)) / cols)


    const colHeight = new Array(cols).fill(0)

    const photos = []

    for (let i = 0, ii = data.length; i < ii; i++) {
        const image = data[i]

        const imgHeight = image.height / image.width * imgWidth

        const pos = i % cols

        const top = colHeight[pos]
        const left = pos ? (imgWidth + gap) * pos : 0

        colHeight[pos] += imgHeight + gap

        let imgStyle = ''
        imgStyle += `top:${top}px;left:${left}px;`;
        imgStyle += `width:${imgWidth}px;height:${imgHeight}px;`

        photos.push({
            style: imgStyle,
            width: imgWidth,
            height: imgHeight,
            url: image.cos_url,
            id: image._id,
        })
    }

    const containerHeight = Math.max(0, ...colHeight)

    return {
        photos,
        colHeight,
        containerHeight
    }

}

 

posted @ 2020-04-23 14:51  vicvinc  阅读(224)  评论(0)    收藏  举报