Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

JavaScript: Find DIV's line-height, not CSS property but actual line-height

Let's say I have a DIV: <div></div> and I want to find out with JS what its line-height is. I know one can check the style attribute style.lineHeight, but I want to check the actual line-height, without it depending on the existence of a CSS rule.

Assuming the font family and font size are the same, both should output the same line-height:

<div>One line of text</div>
<div>Two <br /> Lines of text</div>

How can I get the line-height of an element with JavaScript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...