微信小程序实现滑动删除效果

在一些app中,随处可见左滑动的效果,在微信小程序中,官方并未提供相关组件,需要我们自己动手写一个类似的效果

下面仅列举出核心代码,具体的优化需要根据你自身的需求

<view class='list' wx:if="{{list.length > 0}}">
  <block wx:for="{{list}}" wx:key="list">
    <view class='list_item' bindtap='toResult' data-num='{{item.num}}' data-com='{{item.com}}' bindtouchstart="touchstart" bindtouchmove="touchmove">
      <view class='list_item_img'>
        <image src="../../images/{{item.com}}.png"></image>
      </view>
      <view class='list_item_num {{touchShow ? "touch":""}}'>
        {{item.express_text}}<text>|</text>{{item.num}}
      </view>
      <view class='touchdel' wx:if="{{touchShow}}">
        删除
      </view>
    </view>  
  </block>
</view>

对上述代码做出几点说明:

  1. list 是一个数组,数据源是在对应的页面的js文件里
  2. 主要利用到微信小程序内置的两个事件touchstart和touchmove
  3. 实现原理:通过监听touchstart和touchmove事件,获取clientX,判断clientX是否打到某个阈值,来决定隐藏或显示“删除“ 按钮
.list_item .list_item_num {
  width: 580rpx;
  height: 100rpx;
  line-height: 100rpx;
  text-align: right;
  font-size: 30rpx;
}
.list_item .touch {
  width: 480rpx;
}
.list_item .touchdel {
  width: 120rpx;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  font-size: 30rpx;
  background: #f55757;
  color: #ffffff;
}

上面是相关的css样式

下面是js相关代码(核心)

data: {

list: [],

startX:0,

endX:0

},

touchstart: function (e) {

var startX = e.changedTouches[0].clientX;

console.log('start'+startX);

this.setData({

startX: startX

})

},

touchmove: function (e) {

var endX = e.changedTouches[0].clientX;

console.log('end' + endX);

if(Math.abs(parseInt(endX) - parseInt(this.data.startX)) > 80) {

this.setData({

touchShow: parseInt(endX) - parseInt(this.data.startX) < 0 ? true:false,

endX:endX

})

}

},