V
V
vasIvas2015-11-07 18:06:36
css
vasIvas, 2015-11-07 18:06:36

How do you know the width of the text in 2015?

You need to make a running line, but for this you need to know the width of the text.
I myself did not guess and got into Google, but there articles are either of unknown origin,
or date back to almost seven years ago. But we are on the verge of 2016
and therefore I hope to hear the answer that for a long time it is no longer necessary to turn inside out
to find out the usual width. How to recognize it in pure js?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2015-11-07
@vasIvas

Well, in general, there is a special property
https://developer.mozilla.org/ru/docs/Web/API/Elem...
That is, if the text is in one line, and some part is hidden, say overflow, then this property will return exactly the width all content.

S
Super User, 2015-11-07
@sergeystepanov1988

function getWidthOfText(txt, fontname, fontsize) {
  var c=document.createElement('canvas');
  var ctx=c.getContext('2d');
  ctx.font = fontsize + 'px' + fontname;
  var length = ctx.measureText(txt).width;
  return length;
}

Or:
function getWidthOfText(txt, fontname, fontsize){
  var e=document.createElement('span');
  jQuery(e).text(txt);
  jQuery(e).css({
    'font-size': fontsize,
    'font-family': fontname
  });
  jQuery(e).width();
  delete e;
  return width;
}

Or:
function getWidthOfText(txt, fontname, fontsize){
  var e = document.createElement('span');
  e.style.fontSize = fontsize;
  e.style.fontFamily = fontname;
  e.innerHTML = txt;
  return e.innerWidth;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question