单行文字省略(文字中间省略)
通用的单行省略和多行省略网上有很多这里就不说了,今天分享下文字单行中间省略的实现。有点小GUG,当文字中出现过多的标点符号时省略号位置可能不位于中间。
效果图:

<template>
<div class="ellipsis-wrap">
<span ref="hideText" class="hide-text">{{value}}</span>
<div ref="showText" class="show-text">{{whowVal}}</div>
</div>
</template>
<script>
export default {
data() {
return {
value: '去年的这个时候,我从这扇门里望去,只见那美丽的脸庞和桃,,花彼此相互映衬的绯红。今日再来此地,那丽人已不知所踪,只有桃花依旧,含笑怒放春风之中',
whowVal: ''
};
},
mounted() {
this.computedTextArea();
},
methods: {
computedTextArea() {
const hideWidth = this.$refs.hideText.offsetWidth;
const showWidth = this.$refs.showText.offsetWidth;
console.log(showWidth, hideWidth)
if (hideWidth + 5 >= showWidth) {
const overTextNum = this.computedOverstepTextNum(showWidth, hideWidth)
this.value = this.clipText(this.value, overTextNum)
this.$nextTick(() => {
this.computedTextArea()
})
} else {
this.whowVal = this.value
}
},
// 计算单个文字宽度
computedSingleWordWidth(hideW) {
return hideW / this.value.length
},
// 计算多余的文字
computedOverstepTextNum(showWidth, hideW) {
if (!hideW || !this.value || !showWidth) {
return 0
}
return this.value.length - Math.floor(showWidth / this.computedSingleWordWidth(hideW))
},
// 删除多余文字替换成省略号
clipText(text, overTextNum) {
text = text.replace(/…/g, '');
const startIndex = Math.floor((text.length - overTextNum - 1) / 2);
const delText = text.substr(startIndex, overTextNum + 1);
return text.replace(delText, '…');
}
}
}
</script>
<style lang="less" scoped> .ellipsis-wrap { text-align: left; & > div, & > span { height: 20px; text-align: left; } .hide-text { display: inline-block; white-space: nowrap; overflow: hidden; height: 0; } .show-text { width: 200px; border: 1px solid #ddd; } } </style>

浙公网安备 33010602011771号