css实现移动端文字展开收起 组件 兼容ios

发布于:2022-12-24 ⋅ 阅读:(407) ⋅ 点赞:(0)

移动端文字展开收起 vue项目

要求:

文字超过3行 出现… 和展开按钮 ,点击展开出现收起按钮
文字不超过3行 正常显示

场景

在列表里面作为组件循环使用

效果图如下

![在这里插入图片描述](https://img-blog.csdnimg.cn/72511c06a02f4aa38b1e4eaf7d0fb300.png

代码如下.

<template>
  <div class="text-box">
    <div :class="['txt', { 'over-hidden': !unfold }]" ref="textBox">
      <span ref="spanBox">{{ content }}</span>
    </div>
    <div class="btn" v-if="ifOver" @click="unfold = !unfold">
      {{ unfold ? '收起 ▴' : '展开 ▾' }}
    </div>
  </div>
</template>
<script>
export default {
  name: 'text-content',
  data() {
    return {
      ifOver: false, // 文本是否超出三行,默认否
      unfold: false, // 文本是否是展开状态 默认为收起
    }
  },
  props: {
    content: {
      type: String,
      default: '',
    },
  },
  mounted() {
    // 判断是否显示展开收起按钮
    this.ifOver =
      this.$refs.spanBox.offsetHeight > this.$refs.textBox.offsetHeight
  },
}
</script>
<style scoped>
.text-box {
  margin-top: 6px;
}

.txt {
  margin-bottom: 5px;
  font-weight: 400;
  color: #5a5a5a;
  line-height: 25px;
  font-size: 14px;
  word-break: break-all;
}

.over-hidden {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  word-break: break-all;
  font-weight: 400;
  color: #5a5a5a;
  line-height: 25px;
  font-size: 14px;
}

.btn {
  color: #007ff0;
  line-height: 20px;
  font-size: 14px;
}
</style>

在组件使用的时候 只需要传入一个 text 文本内容就可以了

<TextContent
  :content="item.text"
  :key="item.id"
></TextContent>
本文含有隐藏内容,请 开通VIP 后查看