在网上查看相关解决方案时发现一种大佬实现的很厉害的纯css方案,一开始的组件实现也是基于此,但是很快发现一个问题,因为右侧显示的时候使用 background 来隐藏左侧的文本,但是我们项目用的渐变背景,所以无法这么处理,所以结合 js 对这种方案做了一些改进,使得可以兼容我们的项目~代码如下:
<template>
<div class="text-wrap">
<span ref="textLeft" class="text-left">{{ text }}</span>
<span ref="textRight" class="text-right" :title="text">{{ text }}</span>
</div>
</template>
<script>
export default {
name: 'text-ellipsis-center',
props: {
text: {
type: String,
default: ''
}
},
watch: {
text: {
immediate: true,
handler() {
this.$nextTick(() => {
this.judgeShow()
})
}
}
},
methods: {
judgeShow() {
const textLeftRef = this.$refs.textLeft
const textRightRef = this.$refs.textRight
if (textLeftRef.clientHeight < textRightRef.clientHeight + 1) {
textLeftRef.style.color = '#1d1f24'
} else {
textLeftRef.style.color = 'transparent'
}
}
}
}
</script>
<style lang="less" scoped>
.text-wrap {
width: calc(100vw - 114px);
// width: 300px;
/* 设置正常行高,并隐藏溢出画面 */
height: 2em;
overflow: hidden;
line-height: 2;
position: relative;
text-align: -webkit-match-parent;
// resize: horizontal;
}
.text-left {
/* 设置最大高度为双倍行高使其可以换行 */
display: block;
max-height: 4em;
word-break: break-all;
// color: #1d1f24;
}
.text-right {
position: relative;
top: -4em;
display: block;
color: #1d1f24;
overflow: hidden;
height: 2em;
text-align: justify;
// background: #f7f9fb;
overflow: hidden;
word-break: break-all;
}
.text-right::before {
content: attr(title);
width: 50%;
margin-left: -5px;
float: right;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
direction: rtl;
}
</style>
通过判断当原本的文本 dom 高于右侧高度时,说明发生了换行,这时候不需要显示原本文本,所以进行隐藏,反之则显示
实现原理可以参考这里~
https://juejin.cn/post/7329967013923962895?searchId=20241208205727EA80D9D5FB0511F5EE2C#heading-7