开发者

Calculate width of text node in a block level element using jQuery

Say I have:

<div>Some variable amount of text.</div>

How can I get the width (in pixels) of the text in the div?

Keep in mind that the a开发者_JAVA技巧mount of text will vary unpredictably from div to div.

Thanks!


Sounds like you want the width of the contents, not of the div itself as others have provided. I think that you will need to wrap your contents in a span so that you can then measure the width of the span. The div will always be as wide as possible. You need something that collapses to the size of the content that you can measure instead.


The best way I found is to use CSS rule "display:inline;" to bound only textNode of given HTML Element, then use offsetWidth JS method.

<div style="display:inline;" id="gotWidthInPixels" >Some variable amount of text.</div>
<script>
  //either:
  var widthInPixels= $('#gotWidthInPixels')[0].offsetWidth; 
  //or
  var widthInPixels= document.getElementById("gotWidthInPixels").offsetWidth;
</script>

This will give you exact width in pixels of any HTML Element.


var w = $('div').width()

or use any other selector for the div


Just use width() like so:

<div id="mydiv">text text text</div>
<script>
alert( $('#mydiv').width() );
</script>


with regards to @mrtsherman if you want the width of just the text you could use

var myDiv = $('#myDiv'); 

//div width
var textWidth = sb.width();

//remove padding and margin from left and right
textWidth -= parseInt(sb.css('padding-left') ) + parseInt(sb.css('margin-left') );
textWidth -= parseInt(sb.css('padding-right') ) + parseInt(sb.css('margin-right') );


i had some weird issues where whitespace spaces where breaking the width calculation in jquery. not sure exactly why, if it was because of string variables and concatenation, or the JMVC framework, or just jQuery.

But, making the spaces non-breaking spaces

&nbsp;

seemed to solve it. just throwing that out there in case it helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜