使用小程序動畫實現展開收縮效果


需求:點擊下方優惠信息,展開當前詳情內的全部優惠信息,所在塊自動向上升高,動畫時長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()
        });
      }
})                                

到這里為止就實現了我想要的動畫效果了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM