本文介绍了获取p标签的行高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to figure out the line-height of a <p> tag within a div.

var myp = document.getElementById('myp');
var heightLabel = document.getElementById('heightLabel');
heightLabel.innerHTML = myp.style.lineHeight + " is the height.";
    <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>

但是,如上面的代码所示,如​​果未显式分配p标签的行高,则使用 .style.lineHeight 返回空字符串.

However, as seen in the code above, if the line-height of the p tag is not explicitly assigned then using .style.lineHeight returns an empty string.

如果没有分配< p> 标记中的线的高度,是否有任何方法?我想最后得到px.

Is there any way to get the height of a line in a <p> tag if it hasn't been assigned? I'd like to get it in px at the end.

推荐答案

而不是 .style 属性,您需要将 p 元素

Instead of .style property, you need to getComputedStyle() of your p element

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

之后,您可以简单地使用 elementStyle.getPropertyValue(* style-property *)道具.

After that you can simply use elementStyle.getPropertyValue(*style-property*) prop.

顺便说一句.您可以在控制台下检查计算出的样式(firefox屏幕截图):

Btw. you can check computed style under your console (firefox screenshot):

请参见工作示例:

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>

这篇关于获取p标签的行高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:55