微信小程序表格如何實現表頭固定且滾動流暢?

微信小程序表格:實現表頭固定和流暢滾動

本文解決微信小程序表格中表頭無法固定且滾動不流暢的問題。目標是實現:表頭和左側列固定,右側內容可水平滾動,避免斜向滾動和表頭閃爍。

微信小程序表格如何實現表頭固定且滾動流暢?

問題分析:直接使用ScrollView組件并結合position: sticky和z-index屬性來固定表頭,在處理多方向滾動時存在局限性,容易導致斜向滾動異常、表頭錯位或閃爍。

解決方案:采用嵌套ScrollView組件,外層控制垂直滾動,內層分別控制表頭和表格內容的水平滾動。通過bindscroll事件同步內外層ScrollView的水平滾動位置,實現表頭固定和內容水平滾動的效果。

代碼示例:

WXML:

<scroll-view scroll-y bindscroll="syncScroll" style="height: 100%; width: 100%;">   <view style="width: 100%;">     <scroll-view scroll-x class="scrollHead" id="scrollHead" bindscroll="syncScroll" style="width: 100%; white-space: nowrap;">       <view class="table__head" style="width: {{tableWidth}}rpx;">         <view class="table__head__td" wx:for="{{dataAttribute}}" wx:key="*this">           <text class="table__head__td__text">{{item.title}}</text>         </view>       </view>     </scroll-view>     <scroll-view scroll-x class="scrollBody" id="scrollBody" bindscroll="syncScroll" style="width: 100%; white-space: nowrap;">       <view class="table__row" wx:for="{{data}}" wx:key="*this" style="width: {{tableWidth}}rpx;">         <text class="table__row__td" wx:for="{{dataAttribute}}" wx:key="*this">{{item.key in dataitem ? dataItem[item.key] : '-'}}</text>       </view>     </scroll-view>   </view> </scroll-view>

WXSS:

.scrollHead, .scrollBody {   width: 100%; }  .table__head, .table__row {   display: flex;   justify-content: space-between;   align-items: center;   white-space: nowrap; }  .table__head__td, .table__row__td {   flex: 1;   display: flex;   justify-content: center;   align-items: center; }  .table__head__td__text {   will-change: transform; }

JS:

Page({   data: {     // ... (原有數據) ...     scrollHeadLeft: 0,     scrollBodyLeft: 0   },   syncScroll(e) {     const id = e.currentTarget.id;     const scrollLeft = e.detail.scrollLeft;     if (id === 'scrollHead') {       this.setData({ scrollBodyLeft: scrollLeft });     } else if (id === 'scrollBody') {       this.setData({ scrollHeadLeft: scrollLeft });     }   } });

此方案通過同步兩個scroll-view的水平滾動位置,有效解決了表頭固定和流暢滾動的問題,并避免了斜向滾動和閃爍現象。 請根據實際數據結構調整代碼中的數據綁定。 記得調整css樣式以適應您的實際需求。

? 版權聲明
THE END
喜歡就支持一下吧
點贊9 分享