返回
让多行文本只显示部分,然后可展开...
前端
2023-09-23 23:24:31
在网页上,我们经常会遇到这样的需求:当文本超过一定行数时,隐藏超出部分,只显示部分内容,然后提供一个「查看全部」按钮,点击后展开全部内容。
网上也有人实现过类似的功能,但笔者想自己写一个,于是就写了一个 Vue 的组件。本文将简单介绍一下实现思路。
实现思路
实现这个功能,首先需要确定文本的高度,然后根据高度计算出能显示的行数。接下来,隐藏超出部分的内容,并提供一个按钮来展开全部内容。
具体实现
- 计算文本高度
const textHeight = el.scrollHeight;
- 计算可显示的行数
const lineHeight = parseInt(getComputedStyle(el).lineHeight);
const visibleLines = Math.floor(containerHeight / lineHeight);
- 隐藏超出部分的内容
el.style.height = `${visibleLines * lineHeight}px`;
el.style.overflow = 'hidden';
- 提供「查看全部」按钮
<button @click="toggleShowAll">查看全部</button>
- 「查看全部」按钮的点击事件
toggleShowAll() {
if (this.showAll) {
this.showAll = false;
el.style.height = `${visibleLines * lineHeight}px`;
} else {
this.showAll = true;
el.style.height = 'auto';
}
}
效果
实现后的效果如下图所示:
[图片]
完整代码
<template>
<div>
<p>{{ text }}</p>
<button v-if="!showAll" @click="toggleShowAll">查看全部</button>
</div>
</template>
<script>
export default {
props: ['text'],
data() {
return {
showAll: false,
};
},
mounted() {
const el = this.$el.querySelector('p');
const containerHeight = el.parentElement.offsetHeight;
const textHeight = el.scrollHeight;
const lineHeight = parseInt(getComputedStyle(el).lineHeight);
const visibleLines = Math.floor(containerHeight / lineHeight);
el.style.height = `${visibleLines * lineHeight}px`;
el.style.overflow = 'hidden';
},
methods: {
toggleShowAll() {
const el = this.$el.querySelector('p');
if (this.showAll) {
this.showAll = false;
el.style.height = `${visibleLines * lineHeight}px`;
} else {
this.showAll = true;
el.style.height = 'auto';
}
},
},
};
</script>
总结
以上就是多行文本只显示部分,然后可展开的实现思路和代码。希望本文能对大家有所帮助。