JavaScript 不返回 CSS 设置字体大小

标签 javascript html css fonts size

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/

相关文章:

html - 如何仅使用 CSS 重新排序我的 div?

javascript - 将 div 拆分为每个 div 具有最大高度的 div

javascript - 获取每一行文本元素

javascript - 多个条目后字符串替换然后拆分

javascript - 在 Javascript 实例上绘制图像

javascript - jQuery 背景图像 url

JavaScript 函数无法加载

html - 在图像上定位

html - Bootstrap : How to stack two columns on top of two other columns on small screens?

javascript - 使用 jquery 动画滚动到主页部分