有没有办法在 div 中对长单词进行自动换行?
我知道 Internet Explorer 有自动换行样式,但我想知道是否有跨浏览器方法可以对 div 中的文本执行此操作。
最好是 CSS,但 JavaScript 片段也可以正常工作。
我指的是长字符串。
I know Internet Explorer has a word-wrap style, but I'd like to know if there is a cross-browser method of doing so to text in a div.
Preferably CSS but JavaScript snippets would work ok too.
I'm referring to long strings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以尝试指定 div 的宽度,无论是像素、百分比还是 em,此时 div 将保持该宽度,并且文本将在 div 内自动换行。
You can try specifying a width for the div, whether it be in pixels, percentages or ems, and at that point the div will remain that width and the text will wrap automatically then within the div.
阅读原始评论,卢瑟福正在寻找一种跨浏览器方式来包装不间断文本(通过他在 IE 中使用自动换行来推断,旨在打破不间断的字符串) 。
我已经使用这个类一段时间了,并且效果非常好。 (注:我只在FireFox和IE中测试过)
Reading the original comment, rutherford is looking for a cross-browser way to wrap unbroken text (inferred by his use of word-wrap for IE, designed to break unbroken strings).
I've used this class for a bit now, and works like a charm. (note: I've only tested in FireFox and IE)
之前的大部分答案在 Firefox 38.0.5 中对我不起作用。这确实...
文档:
Most of the previous answer didn't work for me in Firefox 38.0.5. This did...
Documentation:
quirksmode.org/css/whitespace.html
quirksmode.org/css/whitespace.html
Aaron Bennet 的解决方案非常适合我,但我必须从他的代码中删除这一行 -->
white-space: -pre-wrap;
因为它给出了错误,所以最终的工作代码如下:非常感谢
Aaron Bennet's solution is working perfectly for me, but i had to remove this line from his code -->
white-space: -pre-wrap;
beacause it was giving an error, so the final working code is the following:thank you very much
正如 david 提到的,DIV 默认情况下会换行。
如果您指的是非常长的没有空格的文本字符串,我所做的是在服务器端处理字符串并插入空跨度:
这并不准确,因为存在字体大小等问题。如果容器大小可变,则跨度选项有效。如果它是固定宽度的容器,您可以继续插入换行符。
As david mentions, DIVs do wrap words by default.
If you are referring to really long strings of text without spaces, what I do is process the string server-side and insert empty spans:
It's not exact as there are issues with font-sizing and such. The span option works if the container is variable in size. If it's a fixed width container, you could just go ahead and insert line breaks.