In response to the needs of the WeChat applet project, it is necessary to implement a progress bar with a slider that can slide left and right. After reading the documentation of the applet, I found that the progress component above cannot meet the requirements, so I wrote one myself, and summarize it here.
1. Rendering
2. Realize the logic
The logic of function realization is relatively simple, here is a brief explanation:
- First, wrap the relevant code with a label and add static positioning;
- Draw two identical lines, one of them adds relative positioning to change the color of the line, and dynamically sets its width;
- Draw a slider, use relative positioning to fix it on the line, add a bindtouchmove event to it, get its width from the left, and then set it accordingly.
3. Related codes
1. wxml file
<view class="process_wrap">
<view class="line" bindtap="moveTo"></view>
<!-- 这里的宽度和left值也可以改成百分比,效果是一样的 -->
<view class="active_line" style="width:{
{
2*progress}}rpx;" bindtap="moveTo"></view>
<view class="spot" style="left:{
{
2*progress}}rpx" bindtouchmove="moveTo" catchtouchstart="buttonStart"></view>
<view style="margin-top:50rpx;">{
{precent}}%</view>
</view>
2. js file
var startPoint;
const min = 0; // 最小宽度 单位px
const max = 200; // 最大宽度 单位px
Page({
/**
* 页面的初始数据
*/
data: {
buttonLeft: 0,
progress: 0, // 进度条的宽度,这里的单位是px,所以在wxml文件中要改为rpx
precent:0 // 这个是百分比
},
buttonStart: function (e) {
startPoint = e.touches[0]
},
moveTo(e) {
var endPoint = e.touches[e.touches.length - 1]
var translateX = endPoint.clientX - startPoint.clientX
startPoint = endPoint;
var buttonLeft = this.data.buttonLeft + translateX;
if (buttonLeft > max) {
// 滑动位置大于进度条最大宽度的时候让它为最大宽度
buttonLeft = max
}
if (buttonLeft < min) {
// 滑动位置小于进度条最大宽度的时候让它为最小宽度
buttonLeft = min
}
this.setData({
buttonLeft: buttonLeft,
progress: buttonLeft,
precent:parseInt((buttonLeft/max)*100)
})
}
})
3. wxss file
.process_wrap {
position: relative;
width: 400rpx;
margin-left: 60rpx;
}
.process_wrap .line {
width: 400rpx;
height: 2rpx;
background: #B5B8C2;
}
.process_wrap .active_line {
position: absolute;
top: -4rpx;
left: 0;
max-width: 400rpx;
height: 8rpx;
background: linear-gradient(83deg, #84B3FF 0%, #116DF6 100%);
}
.process_wrap .spot {
position: absolute;
top: -20rpx;
left: 0;
width: 40rpx;
height: 40rpx;
background: #1A73FF;
box-shadow: 0px 2px 10px 0px rgba(196, 200, 204, 0.5);
border: 2px solid #FFFFFF;
border-radius: 100%;
}