简体   繁体   English

Javascript:如何判断<span>是否超过2行?

[英]Javascript: how can I tell if a <span> is broken over 2 lines?

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. 只要跨度不超过两条线,气泡就会在该跨度下方居中并且看起来很棒。

Looks good: 看起来不错:

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

Looks bad: 看起来不好

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

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? 有没有办法使用JavaScript或jQuery来判断,如果跨越两行?

9000's comment is correct. 9000的评论是正确的。 The trick is having access to a <span> that you know will be rendered on a single line. 诀窍是可以访问您知道将在一行上呈现的<span> 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; 您可以通过将块的第一个单词包含在具有特定id的范围中来实现,也可以使用最后一个单词或其他单个单词; there are cases where a single word will cross lines but the first word should be safe. 有些情况下,单个单词会交叉,但第一个单词应该是安全的。

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. 一旦你有一个只在一行上的东西,你可以将它的高度与将获得工具提示的<span>的高度进行比较。 If the <span> that is getting the tooltip is taller than the single-line <span> then it has wrapped to multiple lines. 如果获得工具提示的<span>高于单行<span>那么它已经包装到多行。

Try this jsfiddle: 试试这个jsfiddle:

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

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. 我并不为这个黑客感到自豪,但它应该有效。

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> . 也许将鼠标坐标拉出悬停事件并使用它来定位工具提示,而不是根据<span>定位它。

I think the nicer way to do this would be with white-space: nowrap in CSS: 我认为更好的方法是使用white-space: nowrap in CSS:

CSS: CSS:

span.bubble {
    white-space: nowrap;
}

HTML: HTML:

tell <span class="bubble">irregular: told, told</span>

With or without a line break you can just calculate using .css() in jQuery where exactly on the screen is that span located and then position the tooltip accordingly. 无论是否有换行符,你都可以在jQuery中使用.css()进行计算,其中屏幕上恰好位于该跨度位置,然后相应地定位工具提示。 Or you can use a jQuery plugin to do all this for you. 或者您可以使用jQuery插件为您完成所有这些。

不太清楚你正在寻找什么级别的帮助,但是\\n是JS中的换行标识符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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