开发者

What is the best way to wrap label text with jquery?

I need to set a maximum widht to a label tag and avoid the text overflow with开发者_如何学C jquery.

Is there an elegant way to do it?


Specify a width, width: 50px (say), on the label. Since label is an inline element, you also need to specify display: block.

Now, what do you want to do in the case of an overflow? If you simply want to hide the text that doesn't fit, use overflow: hidden. If you want it to wrap to the next line, it'll automatically do this as per the specifications above, unless there is a long piece of non-breakable text (i.e. that doesn't contain any whitespace). In that case, you need to identify the string of characters that would be too long (I've used 15 in the example below), and inject a space between them:

$('#wrap').text($('#wrap').text().replace(/(\S{15})/g, '$1 '));


You could use a class:

... in the css

.elegance{
  overflow:hidden;
  max-width:400px; /* or just width, depending on what you want*/
  display:inline-block;
}

... on document ready

$("label").addClass("elegance");

Or just wrap a div around it using

$("label").wrap("<div class='elegance'></div>");

If you don't want to use separate css, you can set it on the fly using .css()


You can do this:

$("label").wrap("<div style='width: 200px;'></div>");

Or, better overall, use CSS like this:

.labelWrap { width: 200px; }

And jQuery like this to use it:

$("label").wrap($("<div />", {"class":"labelWrap"}));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜