如何用js实现自动换行

在给定html字符串和给定宽度的情况下,如何实现一个高效的wordwrap方法?

var html = `<div>
                <span>The </span><span style="font-size: 24px;">word-break</span><span> CSS property specifies whether or not the browser should insert line breaks wherever the text would otherwise overflow its content box.</span>
            </div>`;
var width = 624;
var result = wordwarp(html, width);
console.log(result);
/* 
<div>
    <span>The </span><span style="font-size: 24px;">word-break</span><span> CSS property specifies whether or not the browser should </span>
</div>
<div>
    <span>insert line breaks wherever the text would otherwise overflow its content box.</span>
</div>
*/
阅读 17.1k
2 个回答

思路大概就是计算出html字符串的长度(str.length * fontSize),
然后在每隔width的地方插入<br>(使用splice)。

上述只是粗略的计算,要较真的话,还得考虑不同字符的长度不一样。
下面提供更精确的方法,思路同上,都是在每隔width的地方插入<br>。区别在于怎么计算出更加精确的字符串长度。

<span id="test-wrap" style="display:inline-block; visibility:hidden;"></span>
let getTest = (str, width) => {
    let span = document.querySelector('#test-wrap');
    for(let i of str) {
        span.innerText += i;
        console.log(span.clientWidth);
        // 当span.clientWidth 与 width 在误差范围内相等时,插入<br>
    }
    
}

大概就是这样子了,
麻烦么? 麻烦!
效率低么? 低!

然而,用JS来处理文本换行本身就是一件麻烦兼效率低下的事情,以上仅供参考。

不太明白什么意思,inline的元素自动换行的,你给外层div设置个宽度,文字自动换行了啊,请说明白点

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题