VUE3中实现“收起”“展开”功能

《好记性不如烂笔头系列》

<template>
    <van-row>
          <div class="roadshowDescValueDiv">
                <div ref="desContent" class="desContent" :class="{ 'show-all': desShowAll }">
                      <span>{{ value }}</span>
                </div>
                <a v-if="desTextRows > 2" class="toggle" @click.prevent="toggleShow">
                      {{ desShowAll ? '收起' : '展开' }}
                </a>
          </div>
    </van-row>
</template>

<script setup lang="ts">
const value = ref(
  '的撒就开了赛大萨达萨多撒的撒就开了赛大萨达萨多撒撒奥所多撒多撒多撒多撒和达萨罗的三大飒飒大看看大家挥洒来看规范化洒落的挥洒鲁大师啥离开达萨罗看电视是的撒就开了赛大萨达萨多撒撒奥所多撒多撒多撒多撒和达萨罗的三大飒飒大看看大家挥洒来看规范化洒落的挥洒鲁大师啥离开达萨罗看电视是的撒就开了赛大萨达萨多撒撒奥所多撒多撒多撒多撒和达萨罗的三大飒飒大看看大家挥洒来看规范化洒落的挥洒鲁大师啥离开达萨罗看电视是撒奥所多撒多撒多撒多撒和达萨罗的三大飒飒大看看大家挥洒来看规范化洒落的挥洒鲁大师啥离开达萨罗看电视是'
);
const desShowAll = ref(false);
const desTextRows = ref(0);

// 使用 watchEffect 监听文本变化和 showAll 变化,更新 textRows
const desContent = ref<any>();
watchEffect(() => {
  if (desContent.value) {
    // 计算文本占据的行数
    const lineHeight = parseFloat(window.getComputedStyle(desContent.value).lineHeight);
    const height = desContent.value.scrollHeight;
    desTextRows.value = Math.ceil(height / lineHeight);
    console.error(lineHeight, height, desTextRows.value);
  }
});
const toggleShow = () => {
  desShowAll.value = !desShowAll.value;
};
</script>
 
<style lang="scss" scoped>
  .roadshowDescValueDiv {
    position: relative;
    .desContent {
      position: relative;
      font-size: 15px;
      line-height: 24px;
      word-break: break-all;
      display: -webkit-box;
      overflow: hidden;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    .show-all {
      -webkit-line-clamp: unset;
    }

    .toggle {
      margin-top: 10px;
      cursor: pointer;
      font-size: 12px;
      font-family: SourceHanSansCN-Regular, SourceHanSansCN;
      font-weight: 400;
      color: #5e58f6;
      line-height: 18px;
    }
  }
</style>
posted @ 2023-06-26 11:12  佐佐木绯世  阅读(1724)  评论(0)    收藏  举报