Sow nothing reap nothing

微信小程序简单实现滑块拖动验证

已有7,614次关注

实现思路:使用微信小程序视图容器movable-view可移动区域movable-view可移动的视图容器实现滑块布局,movable-view绑定bindchange(拖动过程中触发的事件)来获取X轴改变的距离,小程序页面加载时onLoad获取设备宽度,通过area_width容器宽度85%计算出滑块容器总宽度,通过bindtouchend手指触摸动作结束绑定事件判断滑动距离及总宽度,验证是否滑动成功。

效果截图:
微信小程序滑块拖动验证.gif

WXML代码:

<view class="container">

  <view class="goods-validation">
    <movable-area class="validation-content" style="width:{{area_width}}%;background-color:{{areaBgColor}};color:{{areaTextColor}}">{{sliderValdationText}}
      <movable-view 
        class="validation-box" 
        style="width:{{box_width}}px" 
        friction="{{100}}" 
        direction="horizontal" 
        x="{{xDistance}}" 
        damping="{{500}}" 
        bindchange="sliderDrag" 
        bindtouchend="sliderDragOver">
        <view class="validation-movable-icon"></view>
      </movable-view>
    </movable-area>
  </view>

  <view class="goods-validation-text">
    <view>滑块总宽度:{{slidingWidth}}</view>
    <view>滑动距离:{{slidingDistance}}</view>
  </view>

</view>

WXSS代码:

.container{width:100%;min-height:100vh;background-color:rgba(238,239,241,1)}
.goods-validation{width:100%;height: 60rpx;padding: 50rpx 0 0 0;}
.validation-content{height:70rpx;margin:0 auto;border-radius:5rpx;display:flex;justify-content:center;align-items:center;}
.validation-box{height:70rpx;border-radius:5rpx;display:flex;justify-content:center;align-items:center;background-image:linear-gradient(100deg,#fd8649,#fb6e45,#fa5e42);}
.validation-movable-icon{width:40rpx;height:40rpx;background:url(../icon/slider_drag_icon.png) no-repeat center center;background-size:100% 100%}
.goods-validation-text{width:85%;margin:0 auto;text-align:center;margin:50rpx 0 0 0}

JS代码:

Page({

  /**
   * 页面的初始数据
   */
  data: {

    slidingDistance: 0, //滑块滑动距离
    xDistance: 0, //滑块默认距离
    area_width: 85,   //滑块容器总宽度 百分比
    box_width: 40,   //滑块的宽px
    slidingWidth: 0,  //滑动总宽度
    sliderValdationText: '拖动滑块验证',
    areaBgColor: '#fff',
    areaTextColor: '#666'
    
  },

  //生命周期函数--监听页面加载
  onLoad: function () {
    let that = this;
    wx.getSystemInfo({  
      success: function(res){
        var sWidth = Math.floor(res.windowWidth * that.data.area_width / 100 - that.data.box_width)
        that.setData({
          slidingWidth: sWidth
        });
      }
    })
  },

  //拖动滑块触发
  sliderDrag: function(e){
    let that = this;
    that.setData({
      slidingDistance: e.detail.x
    });
  },

  //触摸结束
  sliderDragOver: function(e){     
    var that = this;
    if (that.data.slidingDistance >= that.data.slidingWidth) {
      console.log(that.data.slidingDistance, that.data.slidingWidth);
      that.setData({
        sliderValdationText: '验证成功',
        areaBgColor: '#fd8649',
        areaTextColor: '#fff'
      });
    } else {      
      that.setData({
        xDistance: 0
      })
    }
  }

})

需注意getSystemInfo函数中,返回的windowWidth的设备可使用窗口宽度,单位px。

已自动关闭评论