很快就要放假了。人们话不多,什么也不说。先看效果图。
思路
从以上效果图来看,基本要求包括:
左右滑动一定距离,然后将一张卡的位置向对应的方向移动。卡片滑动时有一定的加速度。如果滑动距离过小,仍然会停留在当前卡上,会有反弹效果。看到这个需求,不熟悉小程序的同学可能会觉得有点麻烦。首先需要计算卡片的位置,然后设置滚动条的位置滚动到指定的位置,在滚动的过程中加入一点加速度.
但是,当你查看小程序的开发文档时,你会发现小程序已经提前为我们编写好了,所以我们只需要进行相关的设置。
实现
滚动视图
左右滑动实际上是在水平方向滚动。小程序为我们提供了滚动视图组件,可以通过设置scroll-x属性来水平滚动。
关键性控制程序
在滚动视图组件属性列表中,我们发现了两个关键属性:
属性类型描述滚动到视图字符串值应该是子元素id(id不能以数字开头)。设置滚动的方向,然后向哪个方向滚动到这个元素。动画滚动布尔型在设置滚动条位置时使用动画过渡。有了这两个属性,我们就可以轻松做事。只要每张卡片都有一页,并且设置了元素的ID,就可以轻松实现翻页效果。
左右滑动判断
这里,我们通过触摸的开始位置和结束位置来确定滑动方向。
微信小程序为我们提供了touchstart和touchend事件,我们可以通过判断开头和结尾的横坐标来判断方向。
代码实现
card.wxml
scroll-view class=' scroll-box ' scroll-x scroll-with-animation scroll-in-view=' { { to view } } ' bind touchStart=' touchStart ' bind touch end=' touch end ' view wx : for=' { { list } } ' wx : key=' { { item } } ' class=' card-box ' id=' card _ { { index } } ' view class=' card ' text { { item } }/text/view/view/scroll-view-wxss card。
页面{ overflow:隐藏;背景# 0D1740}.滚动框{ white-space : nowrap;高度: 105 VH;}.卡盒{ display : inline-block;}.card { display: flexjustice-content : center;align-items:居中;盒子尺寸:边框盒子;高度: 80vh;宽度:80 VW;margin: 5vh 10vwfont-size : 40px;背景# F8F2DCborder-radius : 4px;}card.js
const DEFAULT _ PAGE=0;Page({ startPageX: 0,currentView: DEFAULT_PAGE,data : { to view : ` card _ $ { DEFAULT _ PAGE } `,list: ['Javascript ',' Typescript ',' Java ',' PHP ',' Go '])},Touchstart(e){ this . startpage x=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': '卡片幻灯片','背景色' :' # 0d1740 ','导航栏背景色' :' # 0d1740 ','导航栏文字样式' : '白色' }这些都是本文的内容。我希望向你学习