前言
产品出了新的UI,需要渐变的进度条来呈现砍价进度。在小程序外的HTML,直接使用css3就能实现,且有直观的动画效果;而在小程序本身也提供了进度条的组件,但是却没有提供渐变颜色的接口。看来只好自己实现了。
实现过程
思路
1、构建progress组件
2、使用css实现颜色渐变
3、使用setInterval实现动画效果
在pages下建立以下文件
├─components
│ └─progress
│ progress.js
│ progress.json
│ progress.less
│ progress.wxml
│ progress.wxss
progress.json
{
"component": true
}
progress.wxml
需定义的属性:圆角大小、高度、长度、渐变起始颜色、填充背景颜色
<view style="width:100%;background-color: {{fill}};border-radius:{{radius}}px">
<view style="border-radius:{{radius}}px;height: {{height}}px;background: -webkit-linear-gradient(right, {{from}}, {{to}});width:{{width}};"></view>
</view>
progress.js
Component({
properties: {
bar: {
// bar: {
// height: 30,
// color: ["#fecb24", "#ffff00"],
// value: 100,
// radius: 10,
// fill: "red"
// }
type: Object,
observer: "_change"
}
},
data: {
begin: 0, //进度条起始值
height: 0,//进度条高度
from: "green",//默认颜色
to: "green",//默认颜色
interVal: null,//清除周期函数使用
width: "",//进度百分比
fill: "black",//精度条填充颜色
radius: 0//圆角边框值
},
detached() {
//摧毁倒计时
if (this.data.interVal !== null) clearInterval(this.data.interVal);
},
methods: {
_change(bar, oldVal) {
let from = "green";
let to = "green";
if (bar.color !== undefined) {
if (bar.color.length == 2) {
from = bar.color[0];
to = bar.color[1];
} else if (bar.color.length == 1) {
from = to = bar.color[0];
}
}
let radius = 0;
if (bar.radius !== undefined) {
radius = bar.radius;
}
let fill = "black";
if (bar.fill !== undefined) {
fill = bar.fill;
}
this.setData({
height: bar.height,
from: from,
to: to,
radius: radius,
fill: fill
});
//实现进度条动画效果
let interVal = setInterval(() => {
let begin = this.data.begin;
let max = bar.value;
if (max == 0) {
this.setData({
width: "0%"
});
}
if (begin < max) {
let increment = 1;
if (max > 20 && max <= 40) {
increment = 2;
} else if (max > 40 && max <= 60) {
increment = 3;
} else if (max > 60 && max <= 100) {
increment = 4;
}
let now = begin + increment;
this.setData({
begin: now,
width: (now > max ? max : now) + "%",
interVal: interVal
});
} else {
clearInterval(this.data.interVal);
}
}, 30);
}
}
});
使用方法
在使用的文件的json中,加入
"usingComponents": {
"progress": "/pages/components/progress/progress"
}
在wxml中,加入
<view class="progress">
自定义颜色渐变进度条
<progress bar="{{bar}}"></progress>
</view>
在js中的data,设置进度条配置数据
bar: {
height: 20,//进度条高度
color: ["#fecb24", "#ffff00"],//渐变颜色起始颜色,终止颜色
value: 70,//进度条百分比
radius: 10,//圆角
fill: "red"//进度条背景颜色
}
最终效果
progress.gif
进度条效果