返回

让进度条显示得更有趣——微信小程序自定义toast进度百分比动画组件

前端

微信小程序自定义toast进度百分比动画组件

当我们在开发微信小程序时,常常需要在页面中显示进度条来告知用户当前操作的进度。传统的进度条往往都是以线性的方式显示的,缺乏新意。为了让进度条显示得更加生动和有趣,我们可以使用微信小程序框架自定义一个toast进度百分比动画组件。

项目目录结构

|-- wxml
|   |-- toast-progress.wxml
|-- js
|   |-- toast-progress.js
|-- json
|   |-- toast-progress.json
|-- wxss
|   |-- toast-progress.wxss

效果截图

效果截图

实现步骤

  1. wxml目录下创建toast-progress.wxml文件,并添加以下代码:
<view class="toast-progress-container">
  <view class="toast-progress-mask"></view>
  <view class="toast-progress-wrapper">
    <view class="toast-progress-bar" style="width: {{progress}}%;"></view>
    <view class="toast-progress-text">{{progress}}%</view>
  </view>
</view>
  1. js目录下创建toast-progress.js文件,并添加以下代码:
Component({
  properties: {
    progress: {
      type: Number,
      value: 0,
      observer: function(newVal, oldVal) {
        this.setData({
          animationData: this.getAnimationData(newVal)
        });
      }
    }
  },

  data: {
    animationData: {}
  },

  methods: {
    getAnimationData: function(progress) {
      var animation = wx.createAnimation({
        duration: 300,
        timingFunction: 'linear'
      });

      animation.width(progress + '%').step();

      return animation.export();
    }
  }
});
  1. json目录下创建toast-progress.json文件,并添加以下代码:
{
  "usingComponents": {}
}
  1. wxss目录下创建toast-progress.wxss文件,并添加以下代码:
.toast-progress-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.toast-progress-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.toast-progress-wrapper {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
  background-color: #fff;
  border-radius: 10px;
}

.toast-progress-bar {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-color: #09f;
  transition: width 0.3s linear;
}

.toast-progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 16px;
  color: #fff;
}
  1. 在需要使用toast进度百分比动画组件的页面中,引入toast-progress组件,并设置其progress属性。
<toast-progress progress="{{progress}}"></toast-progress>

这样,我们就自定义了一个实用的toast进度百分比动画组件。希望本文对您有所帮助。

结语

本文介绍了如何使用微信小程序框架自定义一个实用的toast进度百分比动画组件。希望本文对您有所帮助。如果您有任何问题,欢迎随时留言。