<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<style>
* {
margin: 0;
padding: 0;
}
#app {
width: 100vw;
height: 100vh;
overflow: scroll;
position: relative;
background-color: lightgray;
}
.box {
width: 100px;
box-sizing: border-box;
position: absolute;
transition: all 0.75s;
left: 0;
top: 0;
box-shadow: rgba(0, 0, 0, 0.16) 0px 3px 6px, rgba(0, 0, 0, 0.23) 0px 3px 6px;
}
.box img {
width: 100%;
}
/* 进入前状态 */
.fade-enter,
.fade-leave-active {
opacity: 0;
}
/* 进入和离开动画属性 */
.fade-leave-active,
.fade-enter-active {
transition: all 0.5s;
}
/* 解决添加元素占位时无动画,替代 width: 0 与 overflow: hidden */
.fade-move {
transition: all 0.5s;
}
/* 解决删除元素时,其他元素补位无动画 */
.fade-leave-active {
position: absolute; /* 必须为绝对定位 */
}
</style>
</head>
<body>
<div id="app">
<transition-group name="fade">
<div class="box" v-for="(item, index) in arr" :key="item.id">
<img :src="item.img" />
</div>
</transition-group>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
arr: [
{ id: 1, img: './img/1.png' },
{ id: 2, img: './img/2.png' },
{ id: 3, img: './img/3.png' },
{ id: 4, img: './img/4.png' },
{ id: 5, img: './img/5.png' },
{ id: 6, img: './img/6.png' },
{ id: 7, img: './img/7.png' },
{ id: 8, img: './img/8.png' },
],
};
},
mounted() {
waterFullLayout();
const arr = this.arr;
let i = 1;
let timer = setInterval(() => {
this.arr.push({ id: i, img: './img/' + i + '.png' });
i++;
if (i === 9) i = 1;
if (this.arr.length > 200) {
clearInterval(timer);
alert('拉动浏览器窗口试试,看看自适应布局');
}
this.$nextTick(() => {
waterFullLayout();
});
});
function waterFullLayout() {
let pageWidth = document.querySelector('#app').clientWidth;
let itemWidth = document.querySelectorAll('.box')[0].offsetWidth;
let gap = 10;
let nums = Math.floor(pageWidth / (itemWidth + gap));
let heightList = [];
let itemArr = document.querySelectorAll('.box');
let imgLen = itemArr.length;
for (let i = 0; i < imgLen; i++) {
if (i < nums) {
heightList.push(itemArr[i].offsetHeight + gap);
itemArr[i].style.top = gap + 'px';
itemArr[i].style.left = (itemWidth + gap) * i + 'px';
} else {
let minItem = {
minHeight: heightList[0],
minIndex: 0,
};
for (let j = 0; j < heightList.length; j++) {
if (heightList[j] < minItem['minHeight']) {
minItem['minHeight'] = heightList[j];
minItem['minIndex'] = j;
}
}
itemArr[i].style.top = minItem['minHeight'] + gap + 'px';
itemArr[i].style.left = (itemWidth + gap) * minItem['minIndex'] + 'px';
heightList[minItem['minIndex']] =
parseFloat(itemArr[i].style.top) + parseFloat(itemArr[i].offsetHeight);
}
}
}
function debounce(fn, delay) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}
window.onload = function () {
waterFullLayout();
};
window.onresize = debounce(waterFullLayout, 100);
},
methods: {},
});
</script>
</body>
</html>
评论0