当前位置: 首页 > 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>

http://www.lqws.cn/news/125911.html

相关文章:

  • Windows 12确认没了,Win11 重心偏移修Bug
  • kubernetes》》k8s》》kubectl proxy 命令后面加一个
  • Python爬虫实战:研究urlparse库相关技术
  • 艾利特协作机器人:重新定义工业涂胶场景的精度革命
  • 第5篇《中间件负载均衡与连接池管理机制设计》
  • HDFS分布式存储 zookeeper
  • 42、响应处理-【源码分析】-浏览器与PostMan内容协商完全适配
  • 第二章 2.2 数据存储安全风险之数据存储风险分析
  • flask功能使用总结和完整示例
  • MVCC理解
  • 证券交易柜台系统解析与LinkCounter解决方案开发实践
  • NLP学习路线图(二十三):长短期记忆网络(LSTM)
  • 2025最新Java日志框架深度解析:Log4j 2 vs Logback性能实测+企业级实战案例
  • Appium+python自动化(八)- 认识Appium- 下章
  • 【leetcode】9. 回文数
  • 如何通过RL真正提升大模型的推理能力?NVIDIA提出长期强化学习训练框架ProRL
  • 内网穿透之Linux版客户端安装(神卓互联)
  • K8S主机漏洞扫描时检测到kube-服务目标SSL证书已过期漏洞的一种永久性修复方法
  • Python IP可达性检测脚本解析
  • 蓝桥杯17114 残缺的数字
  • NPOI操作EXCEL文件 ——CAD C# 二次开发
  • 【Linux】Linux 环境变量
  • [3-02-01].第13节:三方整合 - Jedis客户端操作Redis
  • 【游戏科学】游戏开发中数学算法的核心与应用
  • 四款主流物联网操作系统(FreeRTOS、LiteOS、RT-Thread、AliOS)的综合对比分析
  • 依赖注入的注解
  • IDEA中微服务指定端口启动
  • 每日Prompt:每天上班的状态
  • 【android bluetooth 协议分析 12】【A2DP详解 2】【开启ble扫描-蓝牙音乐卡顿分析】
  • 在 Android 框架中,接口的可见性规则