首页 > 技术文章 > vue 实现超出两行显示展开收起功能(行数可自定义)

yhhBKY 2020-12-08 15:00 原文

<template>
  <div class="name">
    <span
      :style="{ 'max-height': status ? textHeight : '' }"
      :class="{ statusText: status }"
      class="titleText"
      ref="desc"
    >
      {{ name }}
    </span>
    <span
      v-if="idShowText"
      @click="status = !status"
      :class="{ openSpan: status }"
      class="openClose"
      >{{ status ? "展开" : "收起" }}</span
    >
  </div>
</template>
<script>
export default {
  data() {
    return {
      name:
        "这是一个测试的标题的例子,这是一个测试的标题的例子,这是一个测试的标题的例子这是一个测试的标题的例子,这是一个测试的标题的例子,这是一个测试的标题的例子这是一个测试的标题的例子,这是一个测试的标题的例子,这是一个测试的标题的例子",
      textHeight: null,
      status: false,
      idShowText: false
    };
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.calculateText();
      }, 300);
    });
  },
  methods: {
    calculateText() {
      // 这是默认两行数据的高度,一行的高度可以自定义 可以*3 *4达到三行或者四行显示展示和收起的效果
      let twoHeight = 26 * 2;
      this.textHeight = `${twoHeight}px`;
      let curHeight = this.$refs.desc.offsetHeight;
      console.log("curHeight", curHeight);
      console.log("twoHeight", twoHeight);
      if (curHeight > twoHeight) {
        this.status = true;
        this.idShowText = true;
      } else {
        this.status = false;
        this.idShowText = false;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.name {
  padding-top: 22px;
  margin-bottom: 16px;
  position: relative;
  .titleText {
    font-weight: bold;
    font-size: 18px;
  }
  .openClose {
    font-size: 14px;
    color: #25dbe6;
  }
  .openSpan {
    position: absolute;
    right: 0;
    bottom: 2px;
  }
  .statusText {
    overflow: hidden;
    display: block;
  }
  .statusText:after {
    content: "...";
    position: absolute;
    bottom: 0;
    right: 2px;
    width: 48px;
    padding-left: 30px;
    background: linear-gradient(to right, rgba(255,255,255,0.2), #fff 45%);
  }
}
</style>

这是没有超过两行的样子

这是超过两行展示的样子

 

当然也可以自定义行数,修改下面即可,4代表4行

let twoHeight = 26 * 4;


推荐阅读