Mar*_*ode 4 html javascript css
我想弄清楚<p>div中标签的行高。
var myp = document.getElementById('myp');
var heightLabel = document.getElementById('heightLabel');
heightLabel.innerHTML = myp.style.lineHeight + " is the height.";Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
但是,如上面的代码所示,如果未显式分配p标记的行高,则using .style.lineHeight将返回一个空字符串。
<p>如果未分配标记,是否可以获取标记中的线条高度?我想最后得到px。
取而代之的.style财产,你需要getComputedStyle()你的p元
var elementStyle = window.getComputedStyle(*DOM element*);
Run Code Online (Sandbox Code Playgroud)
之后,您可以简单地使用elementStyle.getPropertyValue(*style-property*)道具。
顺便说一句。您可以在控制台下检查计算样式(firefox屏幕截图):
请参阅工作示例:
var elementStyle = window.getComputedStyle(*DOM element*);
Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1673 次 |
| 最近记录: |