在给定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>
*/
思路大概就是计算出html字符串的长度(str.length * fontSize),
然后在每隔
width
的地方插入<br>
(使用splice)。上述只是粗略的计算,要较真的话,还得考虑不同字符的长度不一样。
下面提供更精确的方法,思路同上,都是在每隔
width
的地方插入<br>
。区别在于怎么计算出更加精确的字符串长度。大概就是这样子了,
麻烦么? 麻烦!
效率低么? 低!
然而,用JS来处理文本换行本身就是一件麻烦兼效率低下的事情,以上仅供参考。