深入解析:前端判断内容文字是否溢出容器,创建临时元素来模拟文本实际宽度
今天遇到一个需求: 对表格某行文字保持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 ).fontFamily tempDiv.style.fontSize = window.getComputedStyle(contentRef).fontSize tempDiv.style.fontWeight = window.getComputedStyle( contentRef ).fontWeight tempDiv.style.letterSpacing = window.getComputedStyle( contentRef ).letterSpacing const analysisDescription = contentRef.textContent // 获取 analysis_description 文本 tempDiv.textContent = analysisDescription document.body.appendChild(tempDiv) const textWidth = tempDiv.offsetWidth document.body.removeChild(tempDiv) const containerWidth = contentRef.clientWidth this.$set(this.isOverflow, index, textWidth > containerWidth) } }) }
{{ item.analysis_description }}