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

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

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

http://www.xdnf.cn/news/11751.html

相关文章:

  • JavaWeb:前后端分离开发-部门管理
  • 第四十二天打卡
  • [特殊字符] 革命性AI提示词优化平台正式开源!
  • sylar--线程模块
  • 电网“逆流”怎么办?如何实现分布式光伏发电全部自发自用?
  • 无监督学习-Complete Guide (较长)
  • yum更换阿里云的镜像源
  • 十六、【前端强化篇】完善 TestCase 编辑器:支持 API 结构化定义与断言配置
  • 极客大挑战 2019 EasySQL 1(万能账号密码,SQL注入,HackBar)
  • c++ stl常用算法
  • Seata 分布式事务 XA 模式
  • iTunes 无法备份 iPhone:10 种解决方法
  • [Java 基础]对象,膜具倒出来的
  • Python训练第四十四天
  • Ubuntu24.04 交叉编译 aarch64 ffmpeg
  • 多分辨率 LCD 的 GUI 架构设计与实现
  • AI基础知识(LLM、prompt、rag、embedding、rerank、mcp、agent、多模态)
  • 【Qt开发】文件
  • 【Linux仓库】冯诺依曼体系结构与操作系统【进程·壹】
  • 一台电脑联网如何共享另一台电脑?网线方式
  • Mermaid 绘图--以企业权限视图为例
  • 【后端开发】goland分布式锁的几种实现方式(mysql,redis,etcd,zookeeper,mq,s3)
  • WordPress子主题RiPro-V5van无授权全开源版(源码下载)
  • 实践篇:利用ragas在自己RAG上实现LLM评估②
  • 【Pandas】pandas DataFrame sample
  • sql server如何创建表导入excel的数据
  • 虚拟斯德哥尔摩症候群:用户为何为缺陷AI辩护?
  • 搭建强化推荐的决策服务架构
  • 【深度学习优化算法】02:凸性
  • 深度探索:如何用DeepSeek重构你的工作流