object.style.fontSize 如果通过 css 设置则返回空。但如果直接在 html 中的对象上使用 style 属性进行设置,则有效。
当通过 CSS 设置时,是否有一些技巧可以使其工作?
例如:
<!DOCTYPE html>
<html lang="en-us">
<head>
<style>
#Set_With_CSS_Style_Sheet
{
font-size:14pt;
}
</style>
</head>
<body onload=loaded()>
<!-- Both of these correctly sets the font size -->
<!-- JavaScript retrieves the font size when set in this manner (via style attribute). -->
<div id="Set_With_Style_Attribute" style="font-size:10pt">CSS Font Size Test:10pt</div>
<!-- JavaScript returns empty when set in this manner (via css style sheet). -->
<div id="Set_With_CSS_Style_Sheet">CSS Font Size Test: 14pt</div>
<script type="text/javascript">
function loaded() {
alert("Set With Style Attribute: " + this.document.getElementById("Set_With_Style_Attribute").style.fontSize);
alert("Set With Style Sheet: " + this.document.getElementById("Set_With_CSS_Style_Sheet").style.fontSize);
}
</script>
</body>
</html>
最佳答案
当字体大小由样式表设置时,fontSize
属性将返回 ""
,而您应该使用 window.getComputedStyle .
window.getComputedStyle(document.getElementById('ID'), null).getPropertyValue('font-size');
关于JavaScript 不返回 CSS 设置字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31573360/