<template>
<div class="wrapper" ref="J_waterfall">
<div
class="wf-item"
v-for="f in images"
:key="f.src"
:style="{
width: f.style.width + 'px',
height: f.style.height + 'px',
top: f.style.top + 'px',
left: f.style.left + 'px'
}"
>
<img :src="f.src" class="wf-img">
</div>
</div>
</template>
<script>
export default {
name: 'image-show',
data () {
return {
images: [],
column: 4,
gap: 10,
itemWidth: 0,
heightArr: [],
query: {}
}
},
mounted () {
this.getQuery()
if (!this.query.name) {
console.error('参数获取失败')
return
}
this.init()
this.getImages()
window.onresize = this.onresize
},
methods: {
init () {
let column = this.column
const elWidth = this.$refs.J_waterfall.offsetWidth
if (elWidth > 1600) {
column = 4
} else if (elWidth >= 992) {
column = 3
} else if (elWidth >= 576) {
column = 2
} else {
column = 1
}
// 计算每个列的宽度
this.itemWidth = (elWidth - (column - 1) * this.gap) / column
this.column = column
this.heightArr = []
},
onresize () {
this.init()
this.images.map(item => {
this.setItemStyle(item)
})
},
getQuery () {
this.query = this.$route.query
},
async getImages () {
for (let i = 0; i < 10; i++) {
// 图片地址
const imageSrc = ''
const image = new Image()
image.src = imageSrc
await new Promise((resolve) => {
image.onload = resolve
})
const item = {
src: imageSrc,
width: image.width,
height: image.height
}
this.setItemStyle(item)
this.images.push(item)
// 在加载过程中出现横向滚动条,重新计算样式
if (document.body.scrollHeight > window.innerHeight ) {
this.onresize()
}
}
},
setItemStyle (item) {
const {column, gap, itemWidth, heightArr} = this
const style = {}
style.width = itemWidth
style.height = item.height / (item.width / itemWidth)
// 判断出第一行的item
// 每一列的高度都会实时放入heightArr中,来判断新的item应该放在那一列
if (heightArr.length < column) {
style.top = 0
style.left = heightArr.length * (itemWidth + gap)
this.heightArr.push(style.height + gap)
} else {
const minIdx = getMinIdx(heightArr)
style.top = heightArr[minIdx]
style.left = minIdx * (itemWidth + gap)
this.heightArr[minIdx] += style.height + gap
}
item.style = style
// 获取数组中最小数的索引
function getMinIdx (arr) {
return arr.indexOf(Math.min(...arr))
}
}
}
}
</script>
<style lang="less" scoped>
.wrapper {
position: relative;
width: 100%;
.wf-item {
position: absolute;
transition: all .5s;
.wf-img {
width: 100%;
height: 100%;
}
}
}
</style>
图片瀑布流展示
最新推荐文章于 2025-02-14 11:04:56 发布