九宮格布局在移動端使用較多,總結一下自己的方法。微信小程序實現三行三列的九宮格
方法1:使用百分比
一個父容器設置寬度為100%,父容器中包含九個小格子,寬度為父容器的33.3%(此處需要自己調試),然后使其橫向排列,三格結束自動擠到下一行排列。
方法二:使用wx:for創建一個三行三列的九宮格。此處就是js中的雙層for循環原理,在小程序中顯示兩個對象的嵌套。第一次循環第一個對象(obj),第二次循環第一個對象中的另外一個對象(obj.items),彈性盒子布局。
- obj:[
- {
- id:0,
- items:[
- { id: 0, src: '../../img/12.jpg', text: '代辦理賠' },
- { id: 1, src: '../../img/12.jpg', text: '拖車' },
- { id: 2, src: '../../img/12.jpg', text: '緊急救援' },
- ],
- },{
- id:1,
- items:[
- { id: 3, src: '../../img/12.jpg', text: '事故車定損' },
- {id: 4, src: '../../img/12.jpg', text: '保險代理' },
- {id: 5, src: '../../img/12.jpg', text: '查勘定損' }
- ]
- },{
- id: 3,
- items1: [
- { id: 6, src: '../../img/12.jpg', text: '數據統計' },
- { id: 7, src: '../../img/12.jpg', text: '修改密碼' },
- { id: 8, src: '../../img/12.jpg', text: '退出登錄' }
- ]
- }
- ],
具體實現如下:
wxml代碼實現簡單樣式搭建:
- <view class="page-zong" wx:for="{{obj}}" wx:key="{{id}}">
- <block wx:for="{{item.items}}" wx:key="{{id}}" wx:for-item="items" >
- <view class="page-section" bindtap="bind" data-name="{{items.text}}">
- <view class="img">
- <image src="{{items.src}}" title="{{items.src}}" alt="{{items.src}}"></image>
- </view>
- <view class="pages-text-zong">
- <text class="pages-text">{{items.text}}</text>
- </view>
- </view>
- </block>
- </view>
js數據的填充:
- obj:[
- {
- id:0,
- items:[
- { id: 0, src: '../../img/12.jpg', text: '代辦理賠' },
- { id: 1, src: '../../img/12.jpg', text: '拖車' },
- { id: 2, src: '../../img/12.jpg', text: '緊急救援' },
- ],
- },{
- id:1,
- items:[
- { id: 3, src: '../../img/12.jpg', text: '事故車定損' },
- {id: 4, src: '../../img/12.jpg', text: '保險代理' },
- {id: 5, src: '../../img/12.jpg', text: '查勘定損' }
- ]
- },{
- id: 3,
- items: [
- { id: 6, src: '../../img/12.jpg', text: '數據統計' },
- { id: 7, src: '../../img/12.jpg', text: '修改密碼' },
- { id: 8, src: '../../img/12.jpg', text: '退出登錄' }
- ]
- }
- ]
wxss的渲染:使用rem和%使其不同屏幕的更合自適應。
- .page-zong{
- width: 102%;(有凹陷的感覺,需調試合適尺寸)
- display: flex;
- flex-direction: row;
- justify-content: space-around;
- margin-left: -1%;
- }
- .page-section{
- flex: 1;
- border: 0.1rem solid lightgray;
- padding: 1rem 0.5rem;
- text-align: center;
- }
- .pages-text{
- font-size: 0.8rem;
- display: inline-block;
- margin: 0.6rem auto 0rem auto;
- font-weight: 600;
- }
- image{
- width: 50%;
- height: 3rem;
- }
新聞熱點
疑難解答