用jQuery检测换行符? [英] detecting line-breaks with jQuery?

查看:149
本文介绍了用jQuery检测换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让jQuery / javascript检测字符串被破坏的位置(为了适应CSS宽度约束),以便在新行的开头之前插入DOM元素?

is it possible to have jQuery/javascript detect where a string is broken (in order to fit into CSS width constraints) so as to insert DOM elements before the beginning of a new line?

推荐答案

我提出了一种方法,但为了你的目的可能会有点过分,所以请考虑到这一点。

I came up with an approach, but it might be overkill for your purposes, so take this into account.

您需要创建元素的克隆,清空原始元素,然后将每个单词移回原始元素。如果高度在任何点发生变化,那么在该单词之前会有一个换行符。使用 $(el).text()可以很简单,但如果内部可以有其他标记,而不仅仅是文本,它会变得更复杂。我试着解释如何在这个答案框中按节点分解它,但发现在jsFiddle中创建一个jQuery插件更容易。链接到这里: http://jsfiddle.net/nathan/qkmse/ Gist )。

You need to create a clone of the element, empty the original, then move each word back into the original element. If the height changes at any point, there's a line-break before that word. This would be fairly simple to do using $(el).text(), but it gets more complicated if there can be other tags inside, not just text. I tried explaining how to break it down by node in this answer box, but found it easier just to create a jQuery plugin in a jsFiddle. Link here: http://jsfiddle.net/nathan/qkmse/ (Gist).

赢了t处理浮动元素一切顺利,还有一些其他情况会崩溃。如果您想要更多选项,或者如果它不适合您的目的,或者如果您不确定如何应用它,我会尽力提供帮助,请告诉我。

It won't handle floated elements all that well, and there are a few other situations where it'll fall over. Let me know if you'd like more options, or if it doesn't quite work for your purposes, or if you're not sure how to apply it and I'll try to help.

这篇关于用jQuery检测换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆