获取p标签的行高

时间:2017-07-07 18:58:48

标签: javascript html css

我想弄清楚div中<p>标记的行高。

&#13;
&#13;
var myp = document.getElementById('myp');
var heightLabel = document.getElementById('heightLabel');
heightLabel.innerHTML = myp.style.lineHeight + " is the height.";
&#13;
    <div> 
      <p id=myp>People assume I'm a boiler ready to explode, <br>but I actually have very low blood pressure, <br>which is shocking to people.</p>
    </div>
    
    <h3 id="heightLabel"></h3>
&#13;
&#13;
&#13;

但是,如上面的代码所示,如​​果未明确指定p标记的行高,则使用.style.lineHeight返回空字符串。

如果没有分配,我有什么方法可以在<p>标记中获得一行的高度?我想最后在px中获取它。

1 个答案:

答案 0 :(得分:4)

而不是.style属性,您需要getComputedStyle()元素的p

var elementStyle = window.getComputedStyle(*DOM element*);

之后,您只需使用elementStyle.getPropertyValue(*style-property*) prop。

顺便说一下。你可以在你的控制台下查看计算机样式(firefox截图):

参见工作示例:

var myp = document.getElementById('myp');
var heightLabel = document.getElementById('heightLabel');
var mypStyle = window.getComputedStyle(myp);
heightLabel.innerHTML = mypStyle.getPropertyValue('line-height') + " is the line height.";

// console.log(mypStyle.getPropertyValue('line-height')); // output 20px 
// console.log(typeof mypStyle.getPropertyValue('line-height')); // string

// Using parseFloat we convert string into value
// Examples: 
// parseFloat('20px') // 20, typeof number
// parseFloat('22.5rem') // 22.5 typeof number
// If you are sure, your string will always contain intenger value use parseInt() instead
// DOES not work cross-browser
// Chrome return line-height normal, firefox '20px'
// var getNumberValue = parseFloat(mypStyle.getPropertyValue('line-height')); // 20, typeof string

console.log(getLineHeight(myp));


// https://stackoverflow.com/questions/4392868/javascript-find-divs-line-height-not-css-property-but-actual-line-height?noredirect=1&lq=1
function getLineHeight(element){
   var temp = document.createElement(element.nodeName);
   temp.setAttribute("style","margin:0px;padding:0px;font-family:"+element.style.fontFamily+";font-size:"+element.style.fontSize);
   temp.innerHTML = "test";
   temp = element.parentNode.appendChild(temp);
   var ret = temp.clientHeight;
   temp.parentNode.removeChild(temp);
   return ret;
}
<div> 
      <p id=myp>People assume I'm a boiler ready to explode, <br>but I actually have very low blood pressure, <br>which is shocking to people.</p>
    </div>
    
    <h3 id="heightLabel"></h3>

相关问题