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

妖精的绣舞 提交于 2019-12-10 08:45:46

问题


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 amount of text will vary unpredictably from div to div.

Thanks!


回答1:


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.




回答2:


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.




回答3:


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

or use any other selector for the div




回答4:


Just use width() like so:

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



回答5:


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') );



回答6:


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.



来源:https://stackoverflow.com/questions/5318612/calculate-width-of-text-node-in-a-block-level-element-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!