📜 ⬆️ ⬇️

Defining text sizes

Perhaps one of you faced with a task in which it would be extremely necessary to know the size of the text block in pixels.

After a little research, it turned out that it is not always possible to obtain this size using conventional methods. Whether jQuery methods, prototype, or the usual reference to DOM parameters.

I would like to share a small function that can create a miracle, and find out the unquestionably required dimensions using cloning.
')


function inlineSize(el) {
// , ,
var hiddenStyle = "left:-10000px;top:-10000px;height:auto;width:auto;position:absolute;" ;

// box
// inline
var clone = document .createElement( 'div' );

// ,
// .
for ( var i in el.style) {
try {
if ((el.style[i] != '' ) && (el.style[i].indexOf( ":" ) > 0)) {
clone.style[i] = el.style[i];
}
} catch (e) {}
}

// , .
// , IE style
document .all ? clone.style.setAttribute( 'cssText' , hiddenStyle) : clone.setAttribute( 'style' , hiddenStyle);

// . .
clone.innerHTML = el.innerHTML

// .
// , parent, iframe?
parent. document .body.appendChild(clone);

// .
var rect = {width:clone.clientWidth,height:clone.clientHeight};

// ...
parent. document .body.removeChild(clone);

// .
return rect;
}


* This source code was highlighted with Source Code Highlighter .


Tested on FF2, FF3, IE7.

At the moment there are plugins for jQuery, extension for prototype and methods in ExtJS that allow you to perform this function and can be even better. However, I wanted to reflect in pure language how it all happens. I hope this code will save some time of your precious life;)

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


All Articles