gpt4 book ai didi

javascript - 在 CSS/JS 中,如何在每第 n 个单词处自动换行?

转载 作者:行者123 更新时间:2023-11-28 08:39:23 28 4
gpt4 key购买 nike

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

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

例如,在换行到下一行之前,我想用 css 或 JavaScript 指定每行只能容纳 25 个单词。

最佳答案

很难每 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>

Note: I've wrapped every 10 words, but you could just as easily wrap after as many words as you want, just replace the 10 in the match regex with 25.

关于javascript - 在 CSS/JS 中,如何在每第 n 个单词处自动换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27887888/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com