使用小程序动画实现展开收缩效果

需求:点击下方优惠信息,展开当前详情内的全部优惠信息,所在块自动向上升高,动画时长0.3为了方便演示demo,我把时长改为1秒),第二次点击重新收缩,显示最上方一条,没有数据时不显示优惠信息区域。

效果图:

html部分:

<!-- 优惠信息 -->
    <view class="discount_wrap" bindtap="toggleDiscountInfo" animation="{{toggleAnimationData}}" wx:if="{{discountInfo.length>0}}">
      <view class="discount" wx:for="{{discountInfo}}" wx:key="index">
        <text class="discount_title">{{item.preferenceName}}:</text>
        <text class="discount_info">{{item.preferenceExplain}}</text>
        <text wx:if="{{discountInfo.length>1&&index===0&&!isExpand}}" class="ellipsis">...</text>
      </view>
    </view>

css部分:

.discount_wrap {
  height: 50rpx;
  overflow: hidden; 
  background-color: #F6F6F6;
}
.discount {
  height: 50rpx;
  padding-left: 50rpx;
  display: flex;
  align-items: center;
}

js部分:

Page({
  data: {
    isExpand: false,
    toggleAnimationData: {} // 优惠信息动画
  },
    // 点击优惠信息效果
    toggleDiscountInfo() {
        // 少于两条数据就不需要展开了
        if (this.data.discountInfo.length < 2) return;
        let animation = wx.createAnimation({
          duration: 1000,
          timingFunction: 'ease-out'
        });
        if (this.data.isExpand) {
          // 如果是展开的,就让它收缩
          animation.height('50rpx').step();
        } else {
          // 如果是收缩的,就让它展开
          // 展开的高度是动态计算的,用一行的高度(50)去乘以数组的数量
          // 这里我曾经想过用height:'auto'这个属性,但是发现没法实现这个动画,所以换成了动态计算它的实际高度
          let height = this.data.discountInfo.length * 50 + 'rpx';
          animation.height(height).step();
        }
        this.setData({
          isExpand: !this.data.isExpand,
          toggleAnimationData: animation.export()
        });
      }
})                                

到这里为止就实现了我想要的动画效果了。

原文地址:https://www.cnblogs.com/chenyn/p/13092922.html