我想计算出一个的行高<p>
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
返回一个空字符串。
有没有什么办法可以得到一行的高度<p>
如果尚未分配标签?我想最后以 px 为单位。
代替.style
财产,你需要getComputedStyle()
你的p
element
var elementStyle = window.getComputedStyle(*DOM element*);
之后你可以简单地使用elementStyle.getPropertyValue(*style-property*)
prop.
顺便提一句。您可以在控制台下检查计算的样式(firefox 屏幕截图):
![](https://i.stack.imgur.com/lgoCL.png)
请参阅工作示例:
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)