我有以下代码:
在我的html中
<h1 id="heading">My Site</h1>在我的css中
#heading{
font-size: 16px;
color: #333333;
}当我在控制台的时候
document.getElementById("heading").style.fontSize它给出:""
但当我做的时候
$("#heading").css("fontSize")它给出:16 it
即使打印整个样式对象,也显示所有空白值,但jquery显示正确的结果。
为什么两者之间有区别?
发布于 2016-06-17 20:47:40
因为jQuery的css函数给出了计算样式,而Element.style.fontSize只给出了内联应用的样式。相当于jQuery代码的普通代码如下:
var heading = document.getElementById("heading");
window.getComputedStyle(heading).getPropertyValue('font-size');这将给出元素的实际字体大小,在应用任何CSS之后。
发布于 2016-06-17 20:47:59
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>
带有样式表样式的()
console.log(window.getComputedStyle(document.getElementById("heading"), null).getPropertyValue("font-size"))#heading{
font-size: 16px;
color: #333333;
}<h1 id="heading">My Site</h1>
https://stackoverflow.com/questions/37890100
复制相似问题