前端判断内容文字是否溢出容器,创建临时元素来模拟文本实际宽度
今天遇到一个需求: 对表格某行文字保持2行,溢出省略号,需要水平垂直居中
这个很简单
.safe-columns-analysis_descriptionT {width: 190px;height: 42px;font-size: 14px;font-weight: 400;color: #ffffff;display: -webkit-box; /* 将元素设置为弹性盒子模型 */-webkit-box-orient: vertical; /* 指定子元素的排列方向为垂直 */-webkit-line-clamp: 2; /* 限制文本显示的行数为两行 */overflow: hidden; /* 隐藏超出部分的文本 */text-align: center; /* 文本水平居中 */text-overflow: ellipsis; /* 显示省略号 */word-break: break-all; /* 防止长单词超出容器宽度 */
}
这样就给客户了,然后客户说一行的文字需要水平垂直居中
这个也简单
.safe-columns-analysis_description {width: 190px;height: 42px;font-size: 14px;font-weight: 400;color: #ffffff;display: flex;align-items: center;justify-content: center;
}
问题就变成了怎么判断文字是否溢出了,最后研究出来创建临时元素来模拟文本宽度
isOverflow: {},this.safeData = resp.data.list || []
this.$nextTick(() => {// 初始检查所有元素的溢出状态this.safeData.forEach((_, index) => {this.checkOverflow(index)})
})
checkOverflow(index) {this.$nextTick(() => {const contentRef = this.$refs[`contentRef-${index}`][0]if (contentRef) {// 创建临时元素来模拟文本宽度const tempDiv = document.createElement('div')tempDiv.style.position = 'absolute'tempDiv.style.visibility = 'hidden'tempDiv.style.whiteSpace = 'nowrap' // 防止换行影响宽度tempDiv.style.fontFamily = window.getComputedStyle(contentRef).fontFamilytempDiv.style.fontSize = window.getComputedStyle(contentRef).fontSizetempDiv.style.fontWeight = window.getComputedStyle(contentRef).fontWeighttempDiv.style.letterSpacing = window.getComputedStyle(contentRef).letterSpacingconst analysisDescription = contentRef.textContent // 获取 analysis_description 文本tempDiv.textContent = analysisDescriptiondocument.body.appendChild(tempDiv)const textWidth = tempDiv.offsetWidthdocument.body.removeChild(tempDiv)const containerWidth = contentRef.clientWidththis.$set(this.isOverflow, index, textWidth > containerWidth)}})}
<div :ref="`contentRef-${index}`":class="[ isOverflow[index]? 'safe-columns-analysis_descriptionT': 'safe-columns-analysis_description']"
>{{ item.analysis_description }}
</div>