本文实例为大家分享了微信小程序实现手风琴折叠面板的具体代码,供大家参考,具体内容如下

目的:折叠面板默认显示其中一项,利用toggle实现元素的显示和隐藏
例如:页面中有四个可折叠元素,默认元素1显示,其余项目内容隐藏;当点击元素2时,元素2显示,其余项目内容隐藏。
初始效果如图:

微信小程序实现手风琴折叠面板

1.wxml部分代码如下:

<view class='item' wx:for="{{items}}" wx:key="index">
    <view class='title' data-index="{{index}}" bindtap='panel'>
        {{item.title}}
    </view>
    <view class='detail' wx:if="{{showIndex == index}}">{{item.text}}</view>
</view>

2.js部分代码如下:

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showIndex: 0, //默认第一个项目显示
    items: [{
      title: '折叠项目1',
      text: '项目1的内容'
    }, {
      title: '折叠项目2',
      text: '项目2的内容',
    }, {
      title: '折叠项目3',
      text: '项目3的内容',
    }]
  },

  panel: function (e) {
    console.log(this.data)
    //获取到当前点击元素的下标
    let index = e.currentTarget.dataset.index;
    //当前显示隐藏内容的元素
    let showIndex = this.data.showIndex;
    if (index != showIndex) {
      this.setData({
        showIndex: index
      })
    } else {
      this.setData({
        showIndex: 0
      })
    }
  },
})

3.css部分代码如下:

.item {
  margin: 10rpx auto;
}
 .item .title {
  font-size: 30rpx;
  height: 60rpx;
  line-height: 60rpx;
  background: #f2f2f2;
  display: flex;
}

.item .detail {
  margin: 10rpx auto;
  font-size: 25rpx;
  line-height: 40rpx;
  text-indent: 2em;
}

最终效果如图所示:

微信小程序实现手风琴折叠面板

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。