javascript - 如何使用 word-wrap: break-word 计算行数?
问题描述
是否可以知道没有换行符但只有“自动换行:断词”的 div 中有多少行?
我怎么知道这个 div 内的总行数?
<div id="content_text" style="word-wrap: break-word; background: red; color: white; width: 100px;">dsadasdasdsadasdasdsadasdasdsadasdasdsadasdas</div>
解决方案
您可以创建一个元素的副本,只在其中放置一个字符并获取高度,即一行的高度:
function getLineHeight(element) {
const copy = element.cloneNode();
copy.style.visibility = 'hidden';
copy.style.position = 'absolute';
copy.textContent = 'a';
element.parentNode.appendChild(copy);
const lineHeight = copy.offsetHeight;
lineHeight.remove();
return lineHeight;
}
然后,您可以按如下方式获取行数:
const linesCount = Math.round(element.offsetHeight / getLineHeight(element));
我希望我没有错过任何东西。
推荐阅读
- javascript - 是否可以“计算”一个数组名称(例如通过连接两个字符串?),以便访问现有数组?
- android - Ktor WebSocket 不支持 Android 土耳其语语言环境?
- maven - Maven 构建失败——DependencyResolutionException
- node.js - Mongodb 擦除已过期的文档(mongoose)
- php - 运行 php artisan serve 时出现致命错误>
- javascript - Github 操作:异步调用太多?
- git - 使用 git 子模块销售 go 模块
- advanced-custom-fields - ACF 扩展 - 块与灵活的内容
- node.js - NodeJS 服务器随机以“终止:15”结尾,但没有其他信息可以找到位置/原因
- python-3.x - 尝试使用旧的 Tensorflow 记录脚本。获取 AttributeError:模块 'tensorflow' 没有属性 'python_io'