Javascript: how can I tell if a <span> is broken over 2 lines?
I display a bubble h开发者_JAVA百科elp 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?
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.
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.
Try this jsfiddle:
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>
.
I think the nicer way to do this would be with white-space: nowrap
in CSS:
CSS:
span.bubble {
white-space: nowrap;
}
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. Or you can use a jQuery plugin to do all this for you.
Not quite sure what levels of help you're looking for, but \n
is the identifier for linebreaks in JS
精彩评论