鍍金池/ 問答/HTML/ 如何用js實(shí)現(xiàn)自動(dòng)換行

如何用js實(shí)現(xiàn)自動(dòng)換行

在給定html字符串和給定寬度的情況下,如何實(shí)現(xiàn)一個(gè)高效的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>
*/
回答
編輯回答
奧特蛋

不太明白什么意思,inline的元素自動(dòng)換行的,你給外層div設(shè)置個(gè)寬度,文字自動(dòng)換行了啊,請(qǐng)說明白點(diǎn)

2018年4月22日 10:09
編輯回答
挽青絲

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

上述只是粗略的計(jì)算,要較真的話,還得考慮不同字符的長(zhǎng)度不一樣。
下面提供更精確的方法,思路同上,都是在每隔width的地方插入<br>。區(qū)別在于怎么計(jì)算出更加精確的字符串長(zhǎng)度。

<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);
        // 當(dāng)span.clientWidth 與 width 在誤差范圍內(nèi)相等時(shí),插入<br>
    }
    
}

大概就是這樣子了,
麻煩么? 麻煩!
效率低么? 低!

然而,用JS來處理文本換行本身就是一件麻煩兼效率低下的事情,以上僅供參考。

2017年8月31日 20:09