JavaScript: Find DIV's line-height, not CSS property but actual line-height
The answer is actually using .clientHeight
. As Gaby said, this is not really reliable/trustworthy. However, it is! Here:
function getLineHeight(el) {
var temp = document.createElement(el.nodeName), ret;
temp.setAttribute("style", "margin:0; padding:0; "
+ "font-family:" + (el.style.fontFamily || "inherit") + "; "
+ "font-size:" + (el.style.fontSize || "inherit"));
temp.innerHTML = "A";
el.parentNode.appendChild(temp);
ret = temp.clientHeight;
temp.parentNode.removeChild(temp);
return ret;
}
"Clone" the properties of your element into a new one, get the new's clientHeight
, delete the temporary element, and return it's height;
Explained at quirksmode : http://www.quirksmode.org/dom/getstyles.html
example: http://www.jsfiddle.net/gaby/UXNs2/
function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
and use it like
getStyle('test', 'line-height' )
This solution works for me. It uses the value of the line-height
property when it has been set explicitly or, when the value has not been set, it calculates the value by finding the difference in the height of the object when its contents are augmented by one line.
function calculateLineHeight (element) {
var lineHeight = parseInt(getStyle(element, 'line-height'), 10);
var clone;
var singleLineHeight;
var doubleLineHeight;
if (isNaN(lineHeight)) {
clone = element.cloneNode();
clone.innerHTML = '<br>';
element.appendChild(clone);
singleLineHeight = clone.offsetHeight;
clone.innerHTML = '<br><br>';
doubleLineHeight = clone.offsetHeight;
element.removeChild(clone);
lineHeight = doubleLineHeight - singleLineHeight;
}
return lineHeight;
}