微信小程序九宫格实现
一、概述
效果图
二、实现
定义数据源
test.js
Page({ /** * 页面数据源 */ data: { iconColor: [ 'red', 'orange', 'yellow', 'green', 'rgb(0,255,255)', 'blue', 'purple' ], iconStyle: [ { "type":"success", "size":30, "color":"#32CD32" }, { "type": "success_no_circle", "size": 30, "color": "orange" }, { "type": "info", "size": 30, "color": "yellow" }, { "type": "warn", "size": 30, "color": "green" }, { "type": "waiting", "size": 30, "color": "rgb(0,255,255)" }, { "type": "cancel", "size": 30, "color": "blue" }, { "type": "download", "size": 30, "color": "purple" }, { "type": "search", "size": 30, "color": "#C4C4C4" }, { "type": "clear", "size": 30, "color": "red" } ] } })
定义样式
test.wxss
/* 九宫格容器布局样式 */ .grid-item-container { display: -webkit-flex; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; border-top: 1rpx solid #D9D9D9; } /* item容器样式 */ .grid-item-child { display:flex; display: -webkit-flex; justify-content:center; flex-direction: column; flex-wrap: wrap; float: left; width: 33.33333333%; height: 200rpx; box-sizing: border-box; background-color: #FFFFFF; border-right: 1rpx solid #D9D9D9; border-bottom: 1rpx solid #D9D9D9; } /* icon样式 */ .grid-item-icon { display:flex; display: -webkit-flex; justify-content:center; } /* 文本样式 */ .grid-item-label { display:flex; display: -webkit-flex; justify-content:center; color: #666; font-size: 14px; }
说明:
使用 display: -webkit-flex;对布局做兼容。
保证每排三个图标的两对对齐,采用:justify-content: space-between;属性。
父元素必须设置 flex-wrap: wrap;属性进行换行,否则会在一排展示。
每个子元素的宽度width: 33.33333333%;按照其占位大小分配。
使用justify-content:center;属性设置元素居中。
使用flex-direction: column;和flex-wrap: wrap;属性设置icon和text元素竖直排列。
test.wxml
<view class='grid-item-container'> <block wx:for="{{iconStyle}}" wx:key="index"> <view class='grid-item-child'> <view> <icon class='grid-item-icon' type='{{item.type}}' size='{{item.size}}' color='{{item.color}}'/> <text class='grid-item-label'>{{item.type}}</text> </view> </view> </block> </view>
本文参考链接:
https://blog.csdn.net/mjb00000/article/details/90513424