小程序不支持table標簽怎么辦
小程序不支持table標簽,但是可以使用css的display: table;來實現表格樣式。
推薦學習:小程序開發
具體實現如下:
1、通過設置js里面的數組對象格式模擬動態后臺獲取的數據,然后將數組對象內容以三個元素為一組組成數組對象格式再合并成一個新的數組對象格式,之所以這樣做就是為了,一行有三個單元格設計的:
Page({ data: { tableData: [{ //模擬動態獲取到的后臺數據:數組對象格式 id: 0, name: 'table-th-cell' }, { id: 1, name: 'table-th-cell' }, { id: 2, name: 'table-th-cell' }, { id: 3, name: 'table-tr-cell' }, { id: 4, name: 'table-tr-cell' }, { id: 5, name: 'table-tr-cell' }, { id: 6, name: 'table-tr-cell' }, { id: 7, name: 'table-tr-cell' }, { id: 8, name: 'table-tr-cell' }, ], threeArray: '', //模擬將后臺獲取到的數組對象數據按照一行3個的單元數據的格式切割成新的數組對象(簡單的說:比如獲取到數組是9個元素,切分成,3個元素一組的子數組) }, onLoad: function() { let that = this; let threeArray = []; // 使用for循環將原數據切分成新的數組 for (let i = 0, len = that.data.tableData.length; i < len; i += 3) { threeArray.push(that.data.tableData.slice(i, i + 3)); } console.log(threeArray); that.setData({ threeArray: threeArray }) }, })
2、設置wxml:
<view class="table"> <block wx:for='{{threeArray}}' wx:key='*this' wx:for-item='oneArray'> <!-- 注意嵌套的數組對象 --> <view class="table-tr" wx:if='{{index<1}}'> <block wx:for='{{oneArray}}' wx:key='id'> <view class="table-th">{{item.name}}</view> </block> </view> <view class="table-tr" wx:else> <block wx:for='{{oneArray}}' wx:key='id'> <view class="table-td">{{item.name}}</view> </block> </view> </block> </view>
3、設置wxss:
.table { display: table; width: 100%; /* border-collapse 屬性設置表格的邊框是否被合并為一個單一的邊框,解決相鄰單元格邊框未合并導致有些邊框變粗的視覺效果 */ border-collapse: collapse; overflow-x: hidden; } .table-tr { display: table-row; width: 100%; height: 200rpx; } .table-th { display: table-cell; font-weight: bold; border: 1px solid black; text-align: center; vertical-align: middle; background-color: #ccc; } .table-td { display: table-cell; border: 1px solid black; text-align: center; vertical-align: middle; }
效果如下: