快放假了,人狠話不多,啥也不說了。先看效果圖。
思路
從上面的效果圖來看,基本的需求包括:
看到這樣的需求,不熟悉小程序的同學(xué),可能感覺有點麻煩。首先需要計算卡片的位置,然后再設(shè)置滾動條的位置,使其滾動到指定的位置,而且在滾動的過程中,加上一點加速度...
然而,當(dāng)你查看了小程序的開發(fā)文檔之后,就會發(fā)現(xiàn)小程序已經(jīng)幫我們提前寫好了,我們只要做相關(guān)的設(shè)置就行。
實現(xiàn)
滾動視圖
左右滑動,其實就是水平方向上的滾動。小程序給我們提供了scroll-view組件,我們可以通過設(shè)置scroll-x屬性使其橫向滾動。
關(guān)鍵屬性
在scroll-view組件屬性列表中,我們發(fā)現(xiàn)了兩個關(guān)鍵的屬性:
屬性 | 類型 | 說明 |
---|---|---|
scroll-into-view | string | 值應(yīng)為某子元素id(id不能以數(shù)字開頭)。設(shè)置哪個方向可滾動,則在哪個方向滾動到該元素 |
scroll-with-animation | boolean | 在設(shè)置滾動條位置時使用動畫過渡 |
有了以上這兩個屬性,我們就很好辦事了。只要讓每個卡片獨占一頁,同時設(shè)置元素的ID,就可以很簡單的實現(xiàn)翻頁效果了。
左滑右滑判斷
這里,我們通過觸摸的開始位置和結(jié)束位置來決定滑動方向。
微信小程序給我們提供了touchstart以及touchend事件,我們可以通過判斷開始和結(jié)束的時候的橫坐標(biāo)來判斷方向。
代碼實現(xiàn)
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" }
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com