Javascript:每 100 个字符后添加中断
例如:
如果我写入长文本,
正在退出页面,我有一个想法来修复它,每 100 个字符之后我可以制作一个
标签。但我不知道该怎么做。
感谢您的帮助!
If I write to long text for example this:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
The text is going out of the page, I have an idea to fix it, after every 100 characters I could make a <br />
tag. But I don't know how to do it.
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需在您希望强制换行的元素上使用以下 CSS 属性:
无需任何 JavaScript!
如果您确实想要使用 JavaScript(出于概念考虑;CSS 更易于访问和使用),那么就继续吧。
哦,还有一件事,如果您使用的字体不是等宽字体(而是比例字体),那么在 100 个字符处截断可能会无效。一行可以有 100 个“i”字符,下一行可以有另外一百个“m”字符,它们的大小非常不同。
哦,还有一件事,你不能只在
innerHTML
上应用正则表达式替换,除非它都是文本。如果那里可能有其他元素,则实际上必须循环遍历节点,仅将该技术应用于文本节点。哦,还有另一件事,别费心了。使用 javascript 执行此操作有太多问题。
Just use the following CSS property on the element that you wish to force wrapping in:
No need for any JavaScript!
If you really want to use JavaScript (for concept; CSS is better for accessibility and ease) then go ahead.
Oh, and another thing, if you're using a font that isn't monospace (but rather, proportional), cutting off at 100 characters could be ineffective. One line could have 100 'i' characters, with the next having another hundred 'm' chars, which are very different in size.
Oh, and another thing, you can't just apply a regex replace on the
innerHTML
unless it's all text. If there could possibly be other elements there, you must actually loop through the nodes, applying the technique to only text nodes.Oh, and another thing, don't bother. Too many problems doing it with javascript.
你可以尝试下面的代码
You can try the following code