快放假了,人狠話不多,啥也不說了。先看效果圖。
思路
從上面的效果圖來看,基本的需求包括:
看到這樣的需求,不熟悉小程序的同學,可能感覺有點麻煩。首先需要計算卡片的位置,然后再設置滾動條的位置,使其滾動到指定的位置,而且在滾動的過程中,加上一點加速度...
然而,當你查看了小程序的開發文檔之后,就會發現小程序已經幫我們提前寫好了,我們只要做相關的設置就行。
實現
滾動視圖
左右滑動,其實就是水平方向上的滾動。小程序給我們提供了scroll-view組件,我們可以通過設置scroll-x屬性使其橫向滾動。
關鍵屬性
在scroll-view組件屬性列表中,我們發現了兩個關鍵的屬性:
屬性 | 類型 | 說明 |
---|---|---|
scroll-into-view | string | 值應為某子元素id(id不能以數字開頭)。設置哪個方向可滾動,則在哪個方向滾動到該元素 |
scroll-with-animation | boolean | 在設置滾動條位置時使用動畫過渡 |
有了以上這兩個屬性,我們就很好辦事了。只要讓每個卡片獨占一頁,同時設置元素的ID,就可以很簡單的實現翻頁效果了。
左滑右滑判斷
這里,我們通過觸摸的開始位置和結束位置來決定滑動方向。
微信小程序給我們提供了touchstart以及touchend事件,我們可以通過判斷開始和結束的時候的橫坐標來判斷方向。
代碼實現
card.wxml
<scroll-view class="scroll-box" scroll-x scroll-with-animation scroll-into-view="{{toView}}" bindtouchstart="touchStart" bindtouchend="touchEnd"> <view wx:for="{{list}}" wx:key="{{item}}" class="card-box" id="card_{{index}}"> <view class="card"> <text>{{item}}</text> </view> </view> </scroll-view>
card.wxss
page{ overflow: hidden; background: #0D1740; } .scroll-box{ white-space: nowrap; height: 105vh; } .card-box{ display: inline-block; } .card{ display: flex; justify-content: center; align-items: center; box-sizing: border-box; height: 80vh; width: 80vw; margin: 5vh 10vw; font-size: 40px; background: #F8F2DC; border-radius: 4px; }
card.js
const DEFAULT_PAGE = 0; Page({ startPageX: 0, currentView: DEFAULT_PAGE, data: { toView: `card_${DEFAULT_PAGE}`, list: ['Javascript', 'Typescript', 'Java', 'PHP', 'Go'] }, touchStart(e) { this.startPageX = e.changedTouches[0].pageX; }, touchEnd(e) { const moveX = e.changedTouches[0].pageX - this.startPageX; const maxPage = this.data.list.length - 1; if (Math.abs(moveX) >= 150){ if (moveX > 0) { this.currentView = this.currentView !== 0 ? this.currentView - 1 : 0; } else { this.currentView = this.currentView !== maxPage ? this.currentView + 1 : maxPage; } } this.setData({ toView: `card_${this.currentView}` }); } })
card.json
{ "navigationBarTitleText": "卡片滑動", "backgroundColor": "#0D1740", "navigationBarBackgroundColor": "#0D1740", "navigationBarTextStyle": "white" }
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com