- wxml
- 并通过data-set将项目的id或者wx:for-index=”idx”的idx传递到js,来判断是哪个项目被滑动;
<block wx:for="{{hotelList}}" wx:for-index="idx">
<navigator url="{{pageurl}}?name={{item.name}}">
<view id="{{item.id}}" class="{{touchObj.isSwapLeft&&touchObj.id==item.id&&touchObj.difX>0?'hideItem':''}}" data-auth="{{item.id}}" bindtouchstart="bindTouchStart" bindtouchmove="bindTouchMove" bindtap="returnPos">
<text class="hotelname">{{item.name}}</text>
<lable class="editItem {{touchObj.isSwapLeft&&touchObj.id==item.id&&touchObj.difX>0?'swapLeft':'noSwapLeft'}}">详情</lable >
<image src="/images/right-arrow.png" class="rightArrow"></image>
</view>
</navigator>
</block>
- wxss
/*列表项样式*/
.editItem{
display: inline-block;
background-color:#1296db;
color: white;
height:100%;
text-align: center;
line-height: 160rpx;
transition: all ease .4s;
font-size: 11pt;
width: 180rpx;
z-index: 999
}
/*该列表项左滑*/
.hideItem{
margin-left: -180rpx;
}
/*该列表项操作按钮左滑-显示*/
.swapLeft{
margin-right: -141rpx;
}
/*该列表项操作按钮右滑-隐藏*/
.noSwapLeft{
margin-right: -340rpx;
}
- js
Page({
data:{
...,
touchObj:{
id:'',//被滑动元素标识
sX:'',//开始滑动水平方向位置
sY:'',//开始滑动竖直方向位置
eX:'',//结束滑动水平方向位置
eY:'',//结束滑动竖直方向位置
difX:'',//水平方向差值
difY:'',//竖直方向差值
isSwapLeft:false//是否触发滑动
}
},
//滑动开始 设置sX,sY
bindTouchStart:COM_FUN.bindTouchStart,
//持续滑动 更新eX,eY,判断difX,difY
bindTouchMove:COM_FUN.bindTouchMove,
//复位
returnPos:function(){
this.data.touchObj.isSwapLeft=false;
this.setData({
touchObj:this.data.touchObj
});
}
})
/**
* 左滑动开始
* bindTouchStart()
*/
function bindTouchStart(e){
this.data.touchObj.id=e.currentTarget.dataset.auth;
this.data.touchObj.sX=e.touches[0].clientX;
this.data.touchObj.sY=e.touches[0].clientY;
}
/**
* 持续向左滑动
* bindTouchMove()
*/
function bindTouchMove(e){
console.log('滑动过程:',e.touches[0].clientX,e.touches[0].clientY);
//计算差值
this.data.touchObj.eX=e.touches[0].clientX;
this.data.touchObj.eY=e.touches[0].clientY;
this.data.touchObj.difX=this.data.touchObj.sX-this.data.touchObj.eX;
this.data.touchObj.difY=this.data.touchObj.sY-this.data.touchObj.eY;
//如果手指左滑距离大于等于40rpx并且上或者下的差值的绝对值小于20rpx时(精度控制),判断为触发了左滑
if(Math.abs(this.data.touchObj.difX)>=40&&Math.abs(this.data.touchObj.difY)<=20){
this.data.touchObj.isSwapLeft=true;
this.setData({
touchObj:this.data.touchObj
});
}
else{
this.data.touchObj.isSwapLeft=false;
this.setData({
touchObj:this.data.touchObj
});
}
}
- 效果图
- 总结
1.使用事件bindtouchstart和bindtouchmove,并获取e参数的touches[0]对象内的一些值
2.操作时要用代码记录下起始的位置、结束的位置、以及判断是否滑动的Boolean值
3.通过Boolean值在视图层进行样式切换操作,提前写好未滑动时列表项的样式、操作按钮的样式和滑动后列表项的样式和操作按钮的样式,并给予一定的transition动画时间
4.操作的精准度标准由difX和difY 来断定