版权声明:未经本人同意不得私自转载 https://blog.csdn.net/qq_40190624/article/details/88222209
需求:在cartArray数组中有多个list,需要遍历出来,当我滑动当前的list的时候其它模块要为false,当前为true,并且判断用户滑动的角度;如果大于30度就视为非滑动
html:
<view wx:esle class='section'>
<block wx:for='{{cartArray}}' wx:key="index">
<!-- 如果item.isTouchMove 为true就给它加上clss属性否则为空 -->
<view class="good_list {{item.isTouchMove ? 'touch-move-active' : ''}}"
bindtouchstart='touchStart'
bindtouchmove='touchmove'
>
<view class='content'>
写入具体遍历的内容
</view>
<!-- 删除 -->
<view class='del' catchtap="del" data-index="{{index}}">删除</view>
</view>
</block>
</view>
css:
.content{
box-sizing: border-box;
padding: 10rpx;
width: 100%;
display: flex;
flex-direction: row;
margin-right:0;
transition: all 0.4s;
transform: translateX(90px);
margin-left: -90px;
}
.del{
background-color: #e4393c;
width: 90px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #fff;
transform: translateX(90px);
transition: all 0.4s;
}
.touch-move-active .content,
.touch-move-active .del {
-webkit-transform: translateX(0);
transform: translateX(0);
}
js:
data: {
cartArray: [],
startX: 0, //开始坐标
startY: 0
},
touchStart(e){//移动前点击的位置
console.log(e)
// 在开始触摸时将所有startTouchMove设置为flase,对当前的为true
this.data.cartArray.forEach(cart =>{
if(cart.isTouchMove)//当istouchMove为true
cart.isTouchMove = false;//其它的对象都为false
})
this.setData({
startX: e.changedTouches[0].clientX,
startY: e.changedTouches[0].clientY,
cartArray: this.data.cartArray
})
},
touchmove(e){//移动的位置,用于计算用户滑动的弧度向左还是向右,移动了多少,可以确定删除功能的显示和隐藏
let index = e.currentTarget.dataset.index;
// 获取开始的x,y坐标
let startX = this.data.startX,
startY = this.data.startY;
// 获取移动的x,x坐标
let touchMoveX = e.changedTouches[0].clientX,
touchMoveY = e.changedTouches[0].clientY;
// 调用计算角度的方法,获取角度
var angel = this.angel({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY })
// 遍历cartArray
this.data.cartArray.forEach((cart, i ) =>{
cart.isTouchMove = false;
// 滑动角度大于30,直接return 视为非滑动意思
if(Math.abs(angel) > 30) return;
// 匹配当前所点击的list和滑动的list
if(i == index){
// 匹配上后判断滑动方向
if (touchMoveX > startX){//左滑动隐藏删除
cart.isTouchMove = false;
}else{
cart.isTouchMove = true;
}
}
})
// 更新数据
this.setData({
cartArray:this.data.cartArray
})
},
angel(start,end){//计算滑动的角度
// console.log(start,end)
// 移动坐标减去对应的开始坐标
var _X = end.X - start.X,
_Y = end.Y - start.Y;
// 返回角度 Math.atan() 返回数字的正切值
return 360 * Math.atan(_Y / _X) / (2 * Math.PI)
},