在CSS / JS中,如何对每个第n个单词进行自动换行?

时间:2015-01-11 13:58:01

标签: javascript html css

我想在我的网页上添加一个段落,但是当我写作时,文字会填满整个屏幕宽度。

<p>Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text </p>

例如,我希望在包装到下一行之前指定每行只有25个单词可以用css或JavaScript。

3 个答案:

答案 0 :(得分:1)

很难包装每25个,但你可以设置一个特定的宽度来包装:

p {
    max-width: 400px;
}
<p>Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text </p>

但是,你仍然可以在n个单词中执行此操作,这可能会导致不一致,因为单词的长度可能不同:

var p = document.getElementById("paragraph").innerText;

p = p.match(/(\S+ ){1,10}/g).join("<br>");

document.getElementById("paragraph").innerHTML = p;
<p id="paragraph">Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text </p>

  

注意:我已经包装了每10个单词,但您可以轻松地在尽可能多的单词后包装,只需将匹配正则表达式中的10替换为{{ 1}}。

答案 1 :(得分:0)

这实际上非常简单,我建议以一定的宽度包装,但是因为你说具体你要包装每25个字,所以你走了:

&#13;
&#13;
Array.prototype.slice.call(document.querySelectorAll("p")).forEach(function(e){
  e.innerHTML = e.innerText.match(/(\S+ ){1,10}/g).join("<br>");
                               //           ^^ number of words to wrap at
});
&#13;
<p>Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text</p>
&#13;
&#13;
&#13;

由于25个字对于堆栈溢出而言太宽,我用10个单词代替,但你可以做任何事情。

真的,我把它写成了三行,但它只是一行JavaScript。

答案 2 :(得分:-1)

您需要指定p宽度或将其放在具有已定义宽度

的容器中

p.longtext {
    width:200px; 
}
<p class='longtext'>Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text </p>