简体   繁体   中英

Wrapping a text on arbitrary non-whitespace characters

I have long namespaces to be displayed in my articles (like MyProject\\Sub\\Level ) and I want them to be wrapped on a backslash character ( \\ ) if the window width is insufficient. How can I implement this using CSS or JS/jQuery?

To tell browsers that a line break is permitted after a character, insert the ZERO WIDTH SPACE (ZWSP) character, U+200B, after the character. In HTML markup, you can use the character reference `​', eg

MyProject\​Sub\​Level

If you add the characters via scripting, you can enter the character itself, using the string literal \​ .

Some old browsers (IE 6) used to have problems with this, but now this approach seems to work better than the alternative, the old <wbr> tag (which was well-supported but has now been messed up in new versions of IE).

One option is to use the soft-hyphen ( &shy; ) around the \\ characters; the soft-hyphen allows a word to break at a given point, appearing only if the word does, in fact, break at that point.

It also doesn't appear in the text if it's copied and pasted (tested in Chromium 19/Ubuntu 11.04); this approach uses replace() and jQuery's html() method with the following HTML:

<ul>
    <li>\some\text\possibly\a\path</li>
    <li>\another\path</li>
    <li>\something\else\also\quite\long</li>
</ul>​

And CSS:

li {
    width: 8em;
    border: 1px solid #000;
}​

jQuery:

$('li').html(function(i, h) {
    return h.replace(/(\\)/g, '&shy;$1&shy;')
});​

JS Fiddle demo .

Obviously, you don't need to use the soft-hyphen on both sides of the \\ character, that was just a demonstration for how it might be used.

An alternative, if you'd rather avoid the appearance of - characters at the break-point, is to use the same approach as above, but instead insert an empty span element, and give it the style display: inline-block; :

jQuery:

$('li').html(function(i, h) {
    return h.replace(/(\\)/g, '$1<span></span>')
});​

CSS:

li {
    width: 8em;
    border: 1px solid #000;
}
li span {
    display: inline-block;
}

JS Fiddle demo .

References:

Use the following css in the element that contains the text:

word-wrap: break-word;

It's a css3 property supported in modern browsers: Google Chrome 6, Internet Explorer 8, Firefox 3, Opera 10 y Safari 5.

Acclaration : It won't break on / character only, it could break on any character of the word according to the stretching of container.

您可能会遵循jQuery上的示例-在正文加载后查找并替换文本,并在每个斜杠后插入一个中断

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM