如何从div的style属性中获取高度?
<div style="height:100px;"></div>
我不能使用.height()
,因为这只会返回元素当前的高度 - 我需要检查样式是否已经设置,然后获取该高度。
如何从div的style属性中获取高度?
<div style="height:100px;"></div>
我不能使用.height()
,因为这只会返回元素当前的高度 - 我需要检查样式是否已经设置,然后获取该高度。
最简单的方法是直接进入style
属性:
var heightStyleValue = $("selector for your element")[0].style.height;
你不想使用jQuery的css
函数,因为它会给你计算后的高度,而不是从style
对象中获取的值。
你不能使用elem.style.height,因为style的命名值具有默认值。如果你真的想知道哪些样式参数已经设置,请将style视为数组。
纯JavaScript:
// get style attributes that were actually set on the element
function getStyle(elem,prop) {
var actuallySetStyles = {};
for (var i = 0; i < elem.style.length; i++) {
var key = elem.style[i];
if (prop == key)
return elem.style[key];
actuallySetStyles[key] = elem.style[key];
}
if (!prop)
return actuallySetStyles;
}
console.log(getStyle(elem,'height'));
console.log(getStyle(elem));
jQuery:
jQuery.fn.extend({
// get style attributes that were set on the first element of the jQuery object
getStyle: function (prop) {
var elem = this[0];
var actuallySetStyles = {};
for (var i = 0; i < elem.style.length; i++) {
var key = elem.style[i];
if (prop == key)
return elem.style[key];
actuallySetStyles[key] = elem.style[key];
}
if (!prop)
return actuallySetStyles;
}
}
console.log(jQuery(elem).getStyle('height'));
console.log(jQuery(elem).getStyle());
height()
一样。 - T.J. Crowderstyle="height: 20px"
,但是css
返回的值是40
。为什么?因为一个!important
样式表规则覆盖了style
的值。(或者因为浏览器在某些情况下忽略了样式值。) - T.J. Crowder我不能使用.height(),因为这只会返回元素的当前高度(...)
这怎么可能?除非你使用了一些!important语句(应该避免),否则样式属性具有比CSS中任何其他内容更高的特异性。因此,height()返回的高度应该是相同的,除非它受到某个其他容器的限制。
但是,为了实现你想要做的事情,你需要做两件事:
使用:
document.getElementById("yourID").style.height;
!important
规则会覆盖内联样式(除非内联样式也是!important
)。有时浏览器不使用样式值。因此,样式属性和高度可能会不同。 - T.J. Crowder