如何在 HTML 中将长行换行而不用空格?

发布于 2024-07-10 23:21:55 字数 389 浏览 10 评论 0原文

如果用户键入没有任何空格或空白的长行,则会因比当前元素更宽而破坏格式。 就像是:

哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈............ ...................................................... ................................................

我尝试过只使用 wordwrap() ,但问题是如果存在链接或其他有效的 HTML,它就会中断。

CSS 中似乎有一些选项,但它们都不适用于所有浏览器。 请参阅 IE 中的自动换行。

你怎么解决这个问题?

If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:

HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA.............................................................................................................................................

I've tried just using wordwrap() in PHP, but the problem with that is if there is a link or some other valid HTML, it breaks.

There seems to be a few options in CSS, but none of them work in all browsers. See word-wrap in IE.

How do you solve this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

み零 2024-07-17 23:21:56

我发布了一个解决方案,它使用 JavaScript 和一个简单的正则表达式来打破长单词,以便可以在不破坏网站布局的情况下对其进行换行。

使用 CSS 和 JavaScript 换行

I have posted a solution which uses JavaScript and a simple Regular Expression to break long word so that it can be wrapped without breaking your website layout.

Wrap long lines using CSS and JavaScript

八巷 2024-07-17 23:21:56

我知道这是一个非常老的问题,因为我遇到了同样的问题,所以我寻找一个简单的解决方案。
正如第一篇文章中提到的,我决定使用 php 函数自动换行。

请参阅以下代码示例以获取信息;-)

<?php
    $v = "reallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglink";
    $v2 = wordwrap($v, 12, "<br/>", true);
?>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <table width="300" border="1">
            <tr height="30">
                <td colspan="3" align="center" valign="top">test</td>
            </tr>
            <tr>
                <td width="100"><a href="<?php echo $v; ?>"><?php echo $v2; ?></a></td>
                <td width="100"> </td>
                <td width="100"> </td>
            </tr>
        </table>
    </body>
</html>

希望这会有所帮助。

I know that this is a really old problem and since I had the same problem I searched for a easy solution.
As mentioned in the first post I decided to use the php-function wordwrap.

See the following code example for information ;-)

<?php
    $v = "reallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglinkreallyreallyreallylonglink";
    $v2 = wordwrap($v, 12, "<br/>", true);
?>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <table width="300" border="1">
            <tr height="30">
                <td colspan="3" align="center" valign="top">test</td>
            </tr>
            <tr>
                <td width="100"><a href="<?php echo $v; ?>"><?php echo $v2; ?></a></td>
                <td width="100"> </td>
                <td width="100"> </td>
            </tr>
        </table>
    </body>
</html>

Hope this helps.

将军与妓 2024-07-17 23:21:55

在 CSS3 中:

word-wrap:break-word

in CSS3:

word-wrap:break-word
小苏打饼 2024-07-17 23:21:55

我试图解决同样的问题,我在这里找到了解决方案:

http://perishablepress.com/ press/2010/06/01/wrapping-content/

解决方案:向容器添加以下 CSS 属性

div {
    white-space: pre;           /* CSS 2.0 */
    white-space: pre-wrap;      /* CSS 2.1 */
    white-space: pre-line;      /* CSS 3.0 */
    white-space: -pre-wrap;     /* Opera 4-6 */
    white-space: -o-pre-wrap;   /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap;  /* HP Printers */
    word-wrap: break-word;      /* IE 5+ */
}

这个想法是使用它们,以便获得更好的跨浏览器兼容性

希望这会有所帮助

I was trying to solve the same problem and I found de solution here:

http://perishablepress.com/press/2010/06/01/wrapping-content/

Solution: adding to the container the following CSS properties

div {
    white-space: pre;           /* CSS 2.0 */
    white-space: pre-wrap;      /* CSS 2.1 */
    white-space: pre-line;      /* CSS 3.0 */
    white-space: -pre-wrap;     /* Opera 4-6 */
    white-space: -o-pre-wrap;   /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap;  /* HP Printers */
    word-wrap: break-word;      /* IE 5+ */
}

The idea is using them all so you get better cross-browser compatibility

Hope this helps

浅浅淡淡 2024-07-17 23:21:55

我喜欢使用 overflow: auto CSS 属性/值配对。 这将以您期望的方式呈现父对象。 如果父级中的文本太宽,则滚动条会出现在对象本身中。 这将使结构保持您想要的外观,并为观看者提供滚动查看更多内容的能力。

编辑:与 overflow:scroll 相比,overflow: auto 的好处在于,使用 auto 时,滚动条仅在存在溢出内容时才会出现。 使用scroll,滚动条始终可见。

I like to use the overflow: auto CSS property/value pairing. This will render the parent object the way you'd expect it to appear. If the text within the parent is too wide, scrollbars appear within the object itself. This will keep the structure the way you want it to look and provide the viewer with the ability to scroll over to see more.

Edit: the nice thing about overflow: auto compared to overflow: scroll is that with auto, the scrollbars will only appear when overflowing content exists. With scroll, the scrollbars are always visible.

寂寞清仓 2024-07-17 23:21:55

我个人还没有使用过它,但 Hyphenator 看起来很有前途。

另请参阅相关(可能重复)问题:

I haven't personally used it, but Hyphenator looks promising.

Also see related (possibly duplicate) questions:

别在捏我脸啦 2024-07-17 23:21:55

我很惊讶没有人提到我最喜欢的解决这个问题的方法之一,(可选换行符)标签。 它在浏览器中得到了很好的支持,并且本质上告诉浏览器它可以插入一个如果需要的话换行。 还有相关的零宽度空格字符 具有相同的含义。

对于提到的用例,在网页上显示用户评论,我假设已经有一些输出格式来防止注入攻击等。因此,每次添加这些 标记很简单单词或链接中的 N 个字符太长。

当您需要控制输出的格式(CSS 并不总是允许您这样做)时,这尤其有用。

I'm surprised that nobody has mentioned one of my favorite solutions to this problem, the <wbr> (optional line-break) tag. It's fairly well-supported in browsers and essentially tells the browser that it can insert a line-break if it's necessary. There's also the related zero-width space character, with the same meaning.

For the use case mentioned, displaying user comments on a web page, I would assume that there is already some output formatting to prevent injection attacks, etc. So it's simple to add these <wbr> tags every N characters in words that are too long, or in links.

This is especially useful when you need control over the format of the output, which CSS doesn't always let you do.

傾城如夢未必闌珊 2024-07-17 23:21:55

我会将帖子放在一个 div 中,该 div 具有固定宽度设置溢出以滚动(或根据内容完全隐藏)。

就像:

#post{
    width: 500px;
    overflow: scroll;
}

但这只是我。

编辑:正如cLFlaVA指出的那样......最好使用auto然后scroll。 我确实同意他的观点。

I would put the post in a div that would have a fixed width setting overflow to scroll (or to hide completely depending on the content).

so like:

#post{
    width: 500px;
    overflow: scroll;
}

But that's just me.

EDIT: As cLFlaVA points out... it is better to use auto then scroll. I do agree with him.

厌倦 2024-07-17 23:21:55

不存在“完美”的 HTML/CSS 解决方案。

该解决方案要么隐藏溢出(即滚动或只是隐藏),要么扩展以适应。 没有魔法。

问:如何将 100 厘米宽的物体放入仅 99 厘米宽的空间中?

答:你不能。

您可以阅读 break-word

编辑

请查看这个解决方案
如何应用换行/延续 进行样式和代码格式化

使用 css或

如何防止长单词破坏我的 div?

There is no "perfect" HTML/CSS solution.

The solutions either hide the overflow (ie scrolling or just hidden) or expand to fit. There is no magic.

Q: How can you fit a 100cm wide object into a space only 99cm wide?

A: You can't.

You can read break-word

EDIT

Please check out this solution
How to apply a line wrap/continuation style and code formatting with css

or

How to prevent long words from breaking my div?

溺ぐ爱和你が 2024-07-17 23:21:55

我通过没有像这样修复右侧边栏来避免这个问题:P

I dodge the problem by not having my right sidebar fixed like that :P

只想待在家 2024-07-17 23:21:55

以下是我在 ASP.NET 中所做的操作:

  1. 将文本字段拆分为空格以获取所有单词
  2. 迭代单词查找长度超过一定数量的单词
  3. 插入每 x 个字符(例如每 25 个字符)。

我查看了其他基于 CSS 的内容这样做的方法,但没有找到任何跨浏览器有效的方法。

Here's what I do in ASP.NET:

  1. Split the text field on spaces to get all the words
  2. Iterate the words looking for words that are longer than a certain amount
  3. Insert every x characters (e.g. every 25 characters.)

I looked at other CSS based ways of doing this, but didn't find anything that worked cross-browser.

世态炎凉 2024-07-17 23:21:55

根据乔恩的建议,我创建的代码:

public static string WrapWords(string text, int maxLength)
    {
        string[] words = text.Split(' ');
        for (int i = 0; i < words.Length; i++)
        {
            if (words[i].Length > maxLength) //long word
            {
                words[i] = words[i].Insert(maxLength, " ");
                //still long ?
                words[i]=WrapWords(words[i], maxLength);
            }
        }
        text = string.Join(" ", words);
        return (text);
    }

based on Jon's suggestion the code that I created:

public static string WrapWords(string text, int maxLength)
    {
        string[] words = text.Split(' ');
        for (int i = 0; i < words.Length; i++)
        {
            if (words[i].Length > maxLength) //long word
            {
                words[i] = words[i].Insert(maxLength, " ");
                //still long ?
                words[i]=WrapWords(words[i], maxLength);
            }
        }
        text = string.Join(" ", words);
        return (text);
    }
孤单情人 2024-07-17 23:21:55

我不想仅仅为了断字而将库添加到我的页面中。
然后我写了一个简单的函数,如下所示,希望对人们有所帮助。

(它被打破了 15 个字符,并在之间应用了“&害羞;”,但您可以在代码中轻松更改它)

//the function:
BreakLargeWords = function (str)
{
    BreakLargeWord = function (word)
    {
        var brokenWords = [];
        var wpatt = /\w{15}|\w/igm;
        while (wmatch = wpatt.exec(word))
        {
            var brokenWord = wmatch[0];
            brokenWords.push(brokenWord);
            if (brokenWord.length >= 15) brokenWords.push("­");
        }
        return brokenWords.join("");
    }

    var match;
    var word = "";
    var words = [];
    var patt = /\W/igm;
    var prevPos = 0;
    while (match = patt.exec(str))
    {
        var pos = match.index;
        var len = pos - prevPos;
        word = str.substr(prevPos, len);

        if (word.length > 15) word = BreakLargeWord(word);

        words.push(word);
        words.push(match[0]);
        prevPos = pos + 1;
    }
    word = str.substr(prevPos);
    if (word.length > 15) word = BreakLargeWord(word);
    words.push(word);
    var text = words.join("");
    return text;
}

//how to use
var bigText = "Why is this text this big? Lets do a wrap <b>here</b>! aaaaaaaaaaaaa-bbbbb-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
var goodText = BreakLargeWords(bigText);

I didn't want to add libraries to my pages just for word breaking.
Then I wrote a simple function which I provide below, hope it helps people.

(It is breaking by 15 characters, and applying "& shy;" between, but you can change it easily in the code)

//the function:
BreakLargeWords = function (str)
{
    BreakLargeWord = function (word)
    {
        var brokenWords = [];
        var wpatt = /\w{15}|\w/igm;
        while (wmatch = wpatt.exec(word))
        {
            var brokenWord = wmatch[0];
            brokenWords.push(brokenWord);
            if (brokenWord.length >= 15) brokenWords.push("­");
        }
        return brokenWords.join("");
    }

    var match;
    var word = "";
    var words = [];
    var patt = /\W/igm;
    var prevPos = 0;
    while (match = patt.exec(str))
    {
        var pos = match.index;
        var len = pos - prevPos;
        word = str.substr(prevPos, len);

        if (word.length > 15) word = BreakLargeWord(word);

        words.push(word);
        words.push(match[0]);
        prevPos = pos + 1;
    }
    word = str.substr(prevPos);
    if (word.length > 15) word = BreakLargeWord(word);
    words.push(word);
    var text = words.join("");
    return text;
}

//how to use
var bigText = "Why is this text this big? Lets do a wrap <b>here</b>! aaaaaaaaaaaaa-bbbbb-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
var goodText = BreakLargeWords(bigText);
爱已欠费 2024-07-17 23:21:55

将零宽度空格 () 添加到字符串中,它将换行。

这是一个 JavaScript 示例:

let longWordWithOutSpace = 'pneumonoultramicroscopicsilicovolcanoconiosis';
// add ​ between every character to make it wrap
longWordWithOutSpace.split('').join('​');

Add the Zero width space () to the string and it will wrap.

Here is a Javacript example:

let longWordWithOutSpace = 'pneumonoultramicroscopicsilicovolcanoconiosis';
// add ​ between every character to make it wrap
longWordWithOutSpace.split('').join('​');
沒落の蓅哖 2024-07-17 23:21:55

! 我不想用 Javascript 使我的代码变得更复杂。
我的开发环境是 Blazor,UI 是针对智能手机的。
该代码有一个文件名列表,其中一些名称很长,没有空格或任何其他帮助字符。
对我来说这有效:
https://developer.mozilla.org/en-US/ docs/Web/CSS/overflow-wrap

overflow-wrap: anywhere;

“overflow-wrap:正常;”不起作用,因为它需要字符串中的空间来换行。
“溢出换行:断词;” 对我不起作用也许是因为它不是一个词或其他东西。 我不知道!

! I did not wanted to make my code more complex with Javascript.
my developing Env was Blazor and UI was for Smartphone.
the Code had a list of file names and some of them where a very long name without space or any other helping Char.
for me this works:
https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap

overflow-wrap: anywhere;

" overflow-wrap: normal; " not work becase it needs space in strings to wrap.
"overflow-wrap: break-word;" not worked for me maybe because it was not a word or something else. I am not sure!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文