Take the width of a text?

Asked

Viewed 1,607 times

0

We usually take the width width of a div or any other tag within the page.

How can one pick up the width of a plain text? For example:

Um texto

How do I know the width this text occupies on the Javascript page?

It’s not the string size, it’s the pixel width.

  • Just wrap the text in a span and capture the attribute offsetWidth his.

3 answers

2

Without being in some element, there is no way. My suggestion is to create a wrapper to store the text and then remove it.

var calculateTextWidth = function(text) {
    var span = document.createElement('span');
    span.innerText = text;

    document.body.appendChild(span);
    var width = span.offsetWidth;
    span.parentNode.removeChild(span);

    return width;
}

Calculating in an empty body and considering default browser styles.

calculateTextWidth('Um texto'); // 64px

2


To catch the width width of a text, you can wrap it in a tag span. The span is a tag like inline which has no effect on layout page. Soon the text would look like this:

<span>Um texto</span>

Now that we have the text inside a tag, it’s easy to know the width it occupies with the code:

console.log($("span").width());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Um texto</span>

With Vanillajs:

console.log(document.body.querySelector("span").offsetWidth);
<span>Um texto</span>

0

Look, I saw that using clientWidth you can get the size of the element where the text is: Element.clientWidth - Web Apis | MDN

But you have to define with CSS the position with Fixed.

var text;
var fs;
function capterWH(){
	var w = text.clientWidth+"px";
	var h = text.clientHeight+"px";
	document.getElementById("result").innerHTML = "Width: "+w+" - Height"+h;
}

function insertText(txt){
	text.innerHTML = txt;
}

function sizeTxt(o){
    if(o == "+"){fs = fs + 1;}
    if(o == "-"){fs = fs - 1;}
	text.style.fontSize = fs+"pt"
}

window.onload = function(){
   text = document.getElementById("Text");
   fs = parseInt(text.style.fontSize);
}
#Text
{
   position: fixed;
}
<i id="result">------------</i><br />
Insira o texto: <input type="text" onchange="insertText(this.value)" value="Um texto" /><input type="button" onclick="capterWH()" value="Tamanho em PX" /><br /><br />
<input type="button" onclick="sizeTxt('-')" value="Diminuir fonte" />
<input type="button" onclick="sizeTxt('+')" value="Aumentar fonte" /><hr />
<p id="Text" style="font-size:12pt;">Um texto</p><br />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.