手搓小程序Collapse折疊面板代碼

廣告也精彩

他不過隨手給你一朵花,你卻紅了臉想用余生做代價。你是我窮極一生都沒有做完的夢,而我是你一念之間穿過的風

大佬在詢問能不能手搓小程序Collapse折疊面板,其實在靈沐小程序的文檔模式中是有一個小案例。追求完美要有過渡動畫,因此學習起來

對于這類效果,能用css堅決不用js;學習一段時間后因內容高度問題,導致css3無法實現,妥協….

單個折疊面板

使用小程序API獲取容器動態高度

wx.createSelectorQuery()

點擊后判斷是展開還是關閉,使用animationIcon動畫進行過渡,整體案例如下

wxml

//wxml
<!-- 單個 -->
<view class="coll-view">
  <view class="coll-title" bindtap="collTap">手搓CollPase組件
    <image class="coll-icon" src="../../images/right.svg" animation="{{collIcoon}}" mode="aspectFit"></image>
  </view>
  <view class="coll-hr"></view>
  <view class="coll-centen" animation="{{collAnimation}}">
    <view class="coll-flex-item" >
      人生就像一杯白開水, 剛開始還是淡淡無味。但漸漸的你就會感到白開水的,甘甜。從苦到甜經歷過多少艱辛,
      經歷過多少坎坷。只要有付出,就會有回報。你所應該擁有的成就。就會有回報。生活就猶如做夢。
      我們心中都有魔鬼,他在夢中吞噬生活的細胞。每個人都應有充實而實在的生活。但我們總會心生魔而看著生活虛浮起來。人都有錯。錯也是對。只是我們不太實在而已。
      塵世是個大廣場,人人匆匆,影子一道道交錯,眩暈如夢魘。我們都在現實中,為現實而對錯。
    </view>
  </view>
</view>

css

/**index.wxss**/
.coll-view {
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 48rpx;
  height: 100%;
  background-color: rgb(250, 250, 250);
}
?
.coll-hr {
  border-top: 1px solid rgb(231, 231, 231);
  margin-top: 30rpx;
}
?
.coll-centen{       
  height: 0;
  overflow: hidden;
}
?
.coll-flex-item{
  padding-top: 30rpx;
  overflow: hidden;
}
.coll-title{
  position: relative;
}
.coll-icon{
  width: 50rpx;
  height: 50rpx;
  position: absolute;
  right: 0rpx;
}

js

// index.js
?
?
Page({
  data: {
    iShow: true,
    collHeight: 0,
    collAnimation: {},
    collIcoon:{},
  },
  onShow() { 
    // 建立內容動畫
    this.collAnimation = wx.createAnimation({
      duration: 300,
      timingFunction: 'linear',
    })
    //建立icon旋轉動畫
    this.animationIcon = wx.createAnimation({
      duration: 300,
      timingFunction: 'linear',
    })
  },
  // 單個折疊面板點擊
  collTap() {
    // 獲取元素高度
    const query = wx.createSelectorQuery();  
    query.selectAll('.coll-flex-item').boundingClientRect();
    query.exec((res) => {
      //判斷是否顯示內容
      if (this.data.iShow == true) {  
        // 動態賦值動畫過渡
        this.collAnimation.height(res[0][0].height).step(); 
        this.animationIcon.rotate(90).step()
        // 導出動畫
        this.setData({
          iShow: !this.data.iShow,
          collAnimation: this.collAnimation.export(),
          collIcoon: this.animationIcon.export(),
        })
      }else{
        // 動態賦值動畫過渡
        this.collAnimation.height(0).step();
        this.animationIcon.rotate(0).step();
         // 導出動畫
        this.setData({
          iShow: !this.data.iShow,
          collAnimation: this.collAnimation.export(),
          collIcoon: this.animationIcon.export(),
        })
      }
    })
  },
})

總結

這是單個折疊面板,如果是多個需要改成一個數組后循環

至少需要2個頭發,繼續學習ing

? 版權聲明

相關文章

暫無評論

none
暫無評論...