Javascript:如何判断& lt; span& gt;打破了两行? [英] Javascript: how can I tell if a <span> is broken over 2 lines?

查看:141
本文介绍了Javascript:如何判断& lt; span& gt;打破了两行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为一些短跨度的元素显示气泡帮助.气泡在该跨度下方居中,只要跨度不超过两行,它们就会看起来很棒.

I display a bubble help for some short span elements. The bubbles are centered below that span and look great as long as the span isn't broken over two lines.

看起来不错:

tell <span>irregular: told, told</span>

看起来很糟糕:

tell <span>irregular: told,
told</span>

这看起来很糟糕,因为气泡不再位于跨度下方.是否可以使用JavaScript或jQuery判断跨度是否超过两行?

It looks bad, because the bubble isn't centered under the span anymore. Is there some way using JavaScript or jQuery to tell, if that span is broken over two lines?

推荐答案

9000的注释正确.诀窍在于可以访问将在单行上呈现的< span> .您可以通过使用特定的 id 将代码块的第一个单词包装在一个范围内来实现此目的,也可以使用最后一个单词或其他某个单词;在某些情况下,单个单词会越线,但第一个单词应该是安全的.

9000's comment is correct. The trick is having access to a <span> that you know will be rendered on a single line. You can do that by wrapping the first word of your block in a span with a specific id, you could also use the last word or some other single word; there are cases where a single word will cross lines but the first word should be safe.

一旦您只拥有一行内容,就可以将其高度与将获得工具提示的< span> 的高度进行比较.如果获取工具提示的< span> 比单行< span> 高,则它已包装成多行.

Once you have something that is only on one line you can compare its height to the height of the <span> that will get the tooltip. If the <span> that is getting the tooltip is taller than the single-line <span> then it has wrapped to multiple lines.

尝试这个jsfiddle:

Try this jsfiddle:

http://jsfiddle.net/ambiguous/JbMhZ/1/

调整右窗格的大小,直到红色文本换行,而绿色文本不换行.然后点击顶部工具栏中的 Run (运行),并在 Result (结果)窗格的底部显示以下内容:

Adjust the size of the right panes until the red text wraps but the green text doesn't. Then hit Run in the toolbar at the top and it should say this at the bottom of the Result pane:

#has-break spans more than one line
#no-break spans only one line

我并不为这种黑客攻击感到骄傲,但它应该可以工作.

I'm not exactly proud of this hack but it should work.

我只是想知道,为您的工具提示提供更好的定位算法是否会是一个更好的主意.也许将鼠标坐标从悬停事件中拉出来,并使用它来定位工具提示,而不是基于< span>

I'm left wondering if a better positioning algorithm for your tooltip would be a better idea. Maybe pull the mouse coordinates out of the hover event and use that to position the tooltip rather than positioning it based on the <span>.

这篇关于Javascript:如何判断&amp; lt; span&amp; gt;打破了两行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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