Javascript text width search

Is there a way to find the width of the text in Javascript (used by jQuery, so happy to use any functions they provide) for the hidden element?

I want to have a graph of nodes. Each node has text inside, and I want the nodes to have a width that allows the text to the limit. So I essentially create a hidden one <div>with some html inside. Then I use jQuery to display these <div>on the chart in the right places. It is important that I know the correct width ahead of time, so I can plot the graph correctly.

UPDATE . To clarify, I need to know how wide the text is while it is hidden. The blender gave the answer below, I hope there will be a less complicated way?

+3
source share
5 answers

What width do you mean? If you mean the width of the element <div>, there is a handy function that does exactly what you need. Play with some of them:

$('#foo').width();
$('#foo').innerWidth();
$('#foo').outerWidth();

As for finding the widthhidden element, I usually do this dirty trick:

var zIndex = $('#foo').css('z-index');

$('#foo').css('z-index', '-10');
$('#foo').css('position', 'absolute');
$('#foo').css('display', 'block');

var fooWidth = $('#foo').width();

$('#foo').css('display', 'none');
$('#foo').css('z-index', zIndex);

There should be an easier way though ...

+1
source
+1
source

divs white-space:nowrap (, ), div, , "white-space: normal

+1

-JQuery. , div id myworkerdiv, .

var myDiv document.getElementById('myworkerdiv'),
width = myDiv.clientWidth || myDiv.scrollWidth;

, (clientHeight || scrollHeight).

0
source

You can use some similar blender method, but use the visibility css property, not the display. Visibility: hidden; preserves the placement of the element, but makes it invisible.

0
source

Source: https://habr.com/ru/post/1795889/


All Articles