我有以下代码:
在我的html
中<h1 id="heading">My Site</h1>
在我的CSS
中#heading{
font-size: 16px;
color: #333333;
}
在控制台时我做
document.getElementById("heading").style.fontSize
它给出:"
但是当我做
时$("#heading").css("fontSize")
它给出: 16px
即使我打印了整个样式对象,Vanilla JavaScript也显示所有空白值,但jQuery显示正确的结果。
为什么两者之间有区别?
,因为jQuery的CSS函数为您提供了计算样式,而element.Style.Fontsize只能为您提供内联应用的样式。等效于jQuery代码的香草将是:
var heading = document.getElementById("heading");
window.getComputedStyle(heading).getPropertyValue('font-size');
应用于任何CSS后,这将为您提供元素的实际字体大小。
document.getElementById("heading").style.fontSize
只会获得以下方式设置的样式:
<h1 id="heading" style="font-size:16px">My Site</h1>`
从样式表中设置样式,请使用GetComputedStyle:
window.getComputedStyle(document.getElementById("heading"), null).getPropertyValue("font-size");
带有内联样式:
console.log(document.getElementById("heading").style.fontSize)
<h1 id="heading" style="font-size:16px">My Site</h1>
带Stylesheet样式
console.log(window.getComputedStyle(document.getElementById("heading"), null).getPropertyValue("font-size"))
#heading{
font-size: 16px;
color: #333333;
}
<h1 id="heading">My Site</h1>