vue 實現超出兩行顯示展開收起功能(行數可自定義)


<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;

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM