Zan*_*ane 6 javascript css dom
我在javascript中制作一个简单的手风琴菜单.我希望能够通过css max-height和min-height值为元素设置紧凑和扩展的高度.出于某种原因,当我尝试在javascript中检索元素的最小高度和最大高度以用于动画时,我得到一个空字符串,而不是像它应该的那样"500px".max-height值在css中设置,例如
#id {
min-height: 40px;
max-height: 500px;
}
全部设置,但是当我在我的javascript中放置一个调试机制时,
alert( item.style.minHeight );
它会弹出一个空的警告框.这种情况发生在Firefox 3.6.2和IE 8中.有人知道为什么javascript拒绝能够获得元素的minHeight和maxHeight吗?
该element.style属性只让你知道在该元素中定义为内联的CSS属性,你应该得到计算出的样式,并不是那么容易以跨浏览器的方式做到,正如其他人所说,IE有自己的方式,通过由其他浏览器实现的element.currentStyle属性,DOM Level 2 标准方式是document.defaultView.getComputedStyle方法.
然而,有IE浏览器的方式和标准方法之间的差异,例如,IE element.currentStyle属性期待您访问的两个或多个单词组成的CCS属性名驼峰(例如maxHeight,fontSize,backgroundColor等),标准的方式希望与性能用破折号分开的话(例如max-height,font-size,background-color等等).
此外,IE element.currentStyle将返回指定单位的所有大小(例如12pt,50%,5em),标准方式将计算实际大小(以像素为单位).
我前段时间做了一个跨浏览器的功能,它允许你以跨浏览器的方式获取计算出的样式:
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
对于某些情况,上述函数并不完美,例如对于颜色,标准方法将以rgb(...)表示法返回颜色,在IE上,它们将在定义时返回它们.
检查此示例.
你需要使用currentStyle...
alert(item.currentStyle.minHeight);
Run Code Online (Sandbox Code Playgroud)
该style属性是指由 Javascript 设置的内容,而不是继承的 CSS。像jQuery这样的库在内部解决了这个问题(以及其他无数的烦恼)。