实现效果:
可以看到图片四周有红色边框,是图片所装载的DIV的边框
图片的长宽是不一样的
装载到DIV的用处是 可以让图片不溢出,但是又不变形(比例变宽或者边长都是不理想的)
做法是父DIV overflow:hidden
可以看到从第三张图片开始显示的是不完整的,溢出盒子的部分hidden了
img的 width:100%
V-for使用的时候,是写在DIV里
<div v-for="po in position" :key= 'po.top+","+po.left' class="smallbox" :style="{ width:'100px' , left:po.left+'px',top:po.top+'px'}">
<img v-lazy="po.src" >
</div>
position是div的绝对定位信息
九宫格的实现原理:
// 从当前第一张显示的图片下标显示到它之后的9张
for (var i = this.currentFirstIndex; i < this.currentFirstIndex + 9; i++) {
var l = parseInt(i % this.col) * (100 + 10)
var t = parseInt(i / this.col) * (100 + 10)
let po = {'left': l, 'top': t, 'src': this.imgArr[i]}
console.log(po)
this.position.push(po)
}
DIV和图片的CSS:
img{
width:100%
}
.smallbox {
background-color: #ccc;
position: absolute;
max-width: 100px;
max-height: 100px;
height: 100px;
margin:100px;
border:1px solid red;
border-radius: 6px;
overflow: hidden;
}
每个图片DIV的位置是absolute
那么九张图片所在的父元素应该是relative的
#box{
position: relative;
border:1px solid red;
height:1500px;
}
这个组件的总代吗:
<template>
<section class="container" > <!--最外层容器-->
<!-- <div v-for="(img,index) in imgArr" :key=index>
<img v-lazy=img>
</div> -->
<div id="box">
<button @click="change">click</button>
<div v-for="po in position" :key= 'po.top+","+po.left' class="smallbox" :style="{ width:'100px' , left:po.left+'px',top:po.top+'px'}">
<img v-lazy="po.src" >
</div>
</div>
</section>
</template>
<script>
export default {
components: {
},
data () {
return {
imgBox: 'imgBox',
imgArr: [],
width: '100px',
height: '100px',
position: [],
col: 3, // 修改这个值,可以改变列数
amountOnePage: 9, // 每一页显示的图片数量
currentFirstIndex: 0 // 当前第一张图片在所有图片中的下标
}
},
created () {
// 吧图片放进数组
for (var i = 2; i <= 73; i++) {
// this.imgArr = require('./pic1/pic' + i + '.jpg')
this.imgArr[i - 2] = require('./pic1/' + 'pic' + i + '.jpg')
}
},
methods: {
change: function () {
// 从当前第一张显示的图片下标显示到它之后的9张
for (var i = this.currentFirstIndex; i < this.currentFirstIndex + 9; i++) {
var l = parseInt(i % this.col) * (100 + 10)
var t = parseInt(i / this.col) * (100 + 10)
let po = {'left': l, 'top': t, 'src': this.imgArr[i]}
console.log(po)
this.position.push(po)
}
}
}
}
</script>
<style lang="less">
*{
padding: 0;
margin: 0;
list-style: none;
}
#box{
position: relative;
border:1px solid red;
height:1500px;
}
.imgBox{
border:1px solid red;
}
img{
width:100%
}
.smallbox {
background-color: #ccc;
position: absolute;
max-width: 100px;
max-height: 100px;
height: 100px;
margin:100px;
border:1px solid red;
border-radius: 6px;
overflow: hidden;
}
</style>