首页 > 解决方案 > 如何使用 word-wrap: break-word 计算行数?

问题描述

是否可以知道没有换行符但只有“自动换行:断词”的 div 中有多少行?

我怎么知道这个 div 内的总行数?

<div id="content_text" style="word-wrap: break-word; background: red; color: white; width: 100px;">dsadasdasdsadasdasdsadasdasdsadasdasdsadasdas</div>

标签: javascriptjquery

解决方案


您可以创建一个元素的副本,只在其中放置一个字符并获取高度,即一行的高度:

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));

我希望我没有错过任何东西。


推荐阅读