手搓小程序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

© 版权声明

相关文章

暂无评论

暂无评论...