vue中,使用css实现多行文本【展开收起】功能
先看看效果:
1.父组件
<template>
<div>
<ul class="ul_list">
<li ref="descRef" v-for="item in list" :key="item.id">
<ListItem :listData="item"></ListItem>
</li>
</ul>
</div>
</template>
<script>
import ListItem from "./module/ListItem";
export default {
name: "ParentPage",
components: { ListItem },
data() {
return {
list: [
{
id: "0",
desc: "123123,456,123123,456,123123,456,123123,456,123123,456,123123,456,",
},
{
id: "1",
desc: "这是文本内容,这是文本内容",
},
{
id: "2",
desc: "这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,这是文本内容,",
},
],
};
}
};
</script>
<style scoped lang="scss">
.ul_list {
width: 200px;
margin: 50px 200px 0;
li {
list-style: none;
border-bottom: 1px solid #ddd;
padding: 10px 0;
border: 1px solid #eee;
border-radius: 8px;
margin: 6px 6px 6px 0;
background: #eee;
padding: 6px;
display: flex;
overflow: hidden;
}
}
</style>
- ListItem 子组件(重点)
<template>
<div ref="listDom" class="item" :class="{ spreadSty: isSpread }">
<div class="btn" v-if="showBtn" @click="isSpread = !isSpread">
{{ isSpread ? "收起>" : "展开>" }}
</div>
<div class="desc">{{ listData.desc }}</div>
</div>
</template>
<script>
export default {
name: "ListItem",
props: {
listData: {
type: Object,
default: () => {},
},
},
data() {
return {
showBtn: false, //是否显示【展开/收起】按钮
isSpread: false,
};
},
watch: {
"listData.id": {
immediate: true,
handler() {
//判断是否显示【展开/收起】按钮
this.$nextTick(() => {
const { clientHeight, scrollHeight } = this.$refs.listDom;
this.showBtn = scrollHeight > clientHeight;
});
},
},
},
};
</script>
<style scoped lang="scss">
.item {
text-align: left;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
text-overflow: ellipsis;
overflow: hidden;
line-height: 20px;
.desc {
word-break: break-all; /*英文换行*/
}
/*重点1 使用伪元素进行浮动*/
&::before {
content: "";
float: right;
/*动态高度,使用负margin, 性能比calc 好一点*/
height: 100%;
margin-top: -20px;
/*height: calc(100% - 20px);*/
}
.btn {
position: relative;
/*重点2 按钮设置浮动,并使用clear: both 将按钮移到文本右下角*/
float: right;
clear: both;
font-size: 14px;
height: 20px;
line-height: 20px;
padding: 0 4px;
background: purple;
cursor: pointer;
color: #fff;
margin-left: 10px;
}
/*重点3 展开时的样式*/
&.spreadSty {
-webkit-line-clamp: 999; /*设置一个足够大的行数就可以了*/
}
}
本文借鉴自:CSS 实现多行文本“展开收起”