当前位置: 首页 > news >正文

前端判断内容文字是否溢出容器,创建临时元素来模拟文本实际宽度

今天遇到一个需求: 对表格某行文字保持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>

相关文章:

  • thymeleaf直接调用Spring Bean中定义的方法
  • Maven 构建缓存与离线模式
  • SSM spring Bean基础配置
  • simulink这边重新第二次仿真时,直接UE5崩溃,然后simulink没有响应
  • linux 故障处置通用流程-36计+1计
  • 比较运算符:==、!=、>、<、>=、<=
  • 【C/C++】进一步介绍idl编码
  • 《动手深度学习》8.2文本预处理—代码分析
  • 运行labelme
  • java day15 (数据库)
  • Oracle实用参考(13)——Oracle for Linux静默安装(1)
  • FAST(Features from Accelerated Segment Test)角检测算法原理详解和C++代码实现
  • dvwa8——SQL Injection(Blind)
  • Hive开窗函数的进阶SQL案例
  • 使用PyQt5的图形用户界面(GUI)开发教程
  • 【hive sql】窗口函数
  • QT聊天项目DAY13
  • C# Wkhtmltopdf HTML转PDF碰到的问题
  • RDMA简介3之四种子协议对比
  • 图神经网络实战——图属性度量方法详解
  • 网站设计中下拉列表怎么做/小广告清理
  • 重庆最便宜的网站建设公司/发广告推广平台
  • 网站项目怎么做/关键词优化课程
  • 莱芜共青团网站/北京seo公司网站
  • 网站建设维护公司/惠州百度关键词优化
  • 凌云网站/站长之家是干什么的