样式效果
html
<div class="container">
<div class="item item-1">1</div>
<div class="item item-2">2</div>
<div class="item item-3">3</div>
<div class="item item-4">4</div>
<div class="item item-5">5</div>
<div class="item item-6">6</div>
<div class="item item-7">7</div>
<div class="item item-8">8</div>
<div class="item item-9">9</div>
</div>
css
.container{
display: grid;
grid-template-columns: repeat(auto-fill, 100px); // 根据屏幕狂帝自适应
grid-template-rows: auto ; // 根据内容自适应
grid-row-gap: 20px; // 单元格之间距离
grid-column-gap: 20px; // 单元格之间距离
}
.item {
width: 100px;
height: 100px; // 一定要有内容高度, 配合上面的auto
border-radius: 5px;
background-color: red;
}
如果想详细学习grid布局的可以看阮一峰的教程,文档地址
js控制
默认样式
实际让位置站空
因此需要注意的问题就是 :
- 需要浏览器大小控制一行显示几个
- 判断当前最后一行补充几个
- 去除掉第一列和最后一列的margin
html:
// html
<div
class="MyMindmap"
ref="MyMindmap">
<!-- 正常数据 -->
<div
class="itemMapCommon"
v-for="item in tableData"
:key="item.id">
</div>
<!-- 占空数据 -->
<div
class="itemMapHidden"
v-for="item in hiddenArray"
:key="'none' + item">
</div>
</div>
css:
// css
.MyMindmap {
display: flex;
width: 100%;
flex-wrap: wrap;
justify-content: space-between;
.itemMapCommon, .itemMapHidden {
width: 172px;
height: 172px;
background-color: #fff;
margin: 5px 5px 10px;
}
}
js(vue):
data () {
return {
tableData: [], // 实际table数据
hiddenArray: [], // 隐藏数据
count: 8, // 一行显示几个
}
}
watch:{
'tableData': 'countSortTableSize',
'count': 'countChange',
}
mounted () {
window.addEventListener('resize', this.countSortTableSize)
},
beforeDestroy () {
window.removeEventListener('resize', this.countSortTableSize)
},
methods: {
// 计算一排显示几个,补足最后一行数据显示个数
countSortTableSize () {
this.$nextTick(() => {
setTimeout(() => {
this.hiddenArray = []
let MyMindmapWidth = this.$refs.MyMindmap.clientWidth
let singleWidth = 172 + 7 // 当前长度加上最小margin长度
let count = Math.floor(MyMindmapWidth / singleWidth)
this.count = count
let yushu = this.tableData.length % count
if (yushu === 0) return
if (this.tableData.length < count) {
this.hiddenArray = []
for (let i = 0; i < count - this.tableData.length; i++) {
this.hiddenArray.push(1)
}
} else {
this.hiddenArray = []
for (let i = 0; i < count - yushu; i++) {
this.hiddenArray.push(1)
}
}
}, 100)
})
},
// 去掉最外侧两层的margin
countChange () {
this.$nextTick(() => {
let allLength = this.tableData.length + this.hiddenArray.length
for (let i = 0; i < allLength; i++) {
this.$refs.MyMindmap.children[i].style['marginLeft'] = 5 + 'px'
this.$refs.MyMindmap.children[i].style['marginRight'] = 5 + 'px'
}
for (let i = 0; i < allLength; i++) {
// 所有行的左边的
if (i % this.count === 0) {
this.$refs.MyMindmap.children[i].style['marginLeft'] = 0
}
// 除了最后一行的右边的
if (i % this.count === 0) {
if (i === 0) continue;
this.$refs.MyMindmap.children[i - 1].style['marginRight'] = 0
}
// 最后一行右边的
if (allLength % this.count === 0) {
this.$refs.MyMindmap.children[allLength - 1].style['marginRight'] = 0
}
}
})
}
}