微信小程序实现多行文本展开、收起(组件)

912 阅读1分钟

效果预览

55f23a924faf683366c80b337825cf6d_.gif

代码

expandText.js
Component({
    properties: {
        text: {
          type: String,
          value: ''
        },
        expandText: {
          type: String,
          value: '展开'
        },
        collapseText: {
          type: String,
          value: '收起'
        }
      },
      data: {
        isExpand: false
      },
      methods: {
        expansionClick() {
          this.setData({
            isExpand: !this.data.isExpand
          })
        }
      }
  })
expandText.wxml
<view class="text_expansion">
    <view class="text_expansion_text {{ isExpand ? 'text_expansion_text_expand' : '' }}">
      <text class="text_expansion_button {{ isExpand ? 'text_expansion_button_up' : '' }}" 
      capture-bind:tap="expansionClick"
      user-select="true">{{ isExpand ? collapseText : expandText }}</text>
      {{ text }}
    </view>
  </view>
expandText.wxss
.text_expansion {
    display: flex;
}

.text_expansion_text {
    position: relative;
    width: 100%;
    font-size: 26rpx;
    font-weight: 400;
    color: #333333;
    line-height: 40rpx;
    overflow: hidden;
    max-height: 160rpx;
    text-align: justify;
}

.text_expansion_text::before {
    content: '';
    float: right;
    height: 100%;
    margin-bottom: -40rpx;
}

.text_expansion_text::after {
    content: '';
    width: 100vw;
    height: 100vh;
    position: absolute;
    box-shadow: inset calc(120rpx - 100vw) calc(1.45em - 100vh) 0 0 #f7f8fa;
    margin-left: -120rpx;
}

.text_expansion_button {
    position: relative;
    font-size: 24rpx;
    font-weight: bold;
    float: right;
    clear: both;
    line-height: 42rpx;
}

.text_expansion_button::before {
    content: '...';
    margin-right: 8rpx;
}

.text_expansion_button::after {
    content: '';
    display: inline-block;
    margin-bottom: 2rpx;
    margin-left: 4rpx;
    transition: transform 0.3s;
    border-top: 10rpx solid #002753;
    border-left: 8rpx solid transparent;
    border-right: 8rpx solid transparent;
}

.text_expansion_text_expand {
    max-height: none;
}

.text_expansion_text_expand::after {
    visibility: hidden;
}

.text_expansion_button::before {
    visibility: hidden;
}

.text_expansion_button_up::after {
    transform: rotate(180deg);
}

最后

代码参考:juejin.cn/post/702551…

做一个备份,以后直接拿过来用即可