wxml
1<view class="container" >
2 <view class="slide-box"
3 style="transform: translateX(-{{translateX}}rpx);transition: transform .8s "
4 bindtouchstart="handleTouchStart"
5 bindtouchmove="handleTouchMove"
6 bindtouchend="handleTouchEnd"
7 >
8 <view class="slide-left" >
9 <slot name="slideLeft"></slot>
10 </view>
11 <view class="slide-right" style="width:{{slideWidth}}rpx">
12 <slot name="slideRight"></slot>
13 </view>
14 </view>
15</view>
16
js
1Component({
2 options: {
3 multipleSlots: true,
4 },
5 properties: {
6 slideWidth: { // 右侧滑块的width
7 type: Number,
8 value: 0,
9 },
10 },
11 data: {scroll: true, touches: [], translateX: 0},
12 methods: {
13 /* 计算滑动角度
14 * @param {Object} start 起点坐标
15 * @param {Object} end 终点坐标
16 */
17 handleAngle(start, end) {
18 var _X = end.clientX - start.clientX;
19 var _Y = end.clientY - start.clientY;
20 // 返回角度 /Math.atan()返回数字的反正切值
21 return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
22 },
23 // 触摸开始
24 handleTouchStart(e) {
25 const {touches} = e;
26 // @touches typeof Array
27 // touches.length 手指触摸屏幕的个数
28 this.data.scroll = touches.length === 1;
29 this.data.touches = e.touches;
30 },
31 handleTouchMove(e) {
32 if (this.data.scroll) {
33 // 滑滑动的角度
34 let angle = this.handleAngle(this.data.touches[0], e.touches[0]);
35 // 滑滑动的角度 如果 > 30 不做操作
36 if (Math.abs(angle) > 40) return;
37 // PosX 手指在X轴的坐标差 判断滑动方向
38 let PosX = e.touches[0].pageX - this.data.touches[0].pageX;
39 // PosX < -50 => Left 左滑
40 // PosX > 50 => Right 右滑
41 if (PosX < -50) {
42 this.setData({
43 translateX: this.properties.slideWidth,
44 });
45 }
46 else if (PosX > 50) {
47 this.setData({
48 translateX: 0,
49 });
50 }
51 }
52 },
53
54 // 触摸结束
55 handleTouchEnd(e) {
56 this.data.scroll = false;
57 },
58 },
59 pageLifetimes: {
60 // 组件所在页面的生命周期函数
61 hide: function () {
62 this.setData({
63 translateX: 0,
64 });
65 },
66 },
67});
68
wxs
1.container{
2 position: relative;
3 padding: 0;
4 overflow: hidden;
5}
6
7
8.container .slide-box{
9 position: relative;
10 min-height: 40rpx;
11}
12
13
14.slide-right{
15 position: absolute;
16 top: 0;
17 bottom: 0;
18 left: 100%;
19
20}
21
json
1{
2 "component": true
3}