论坛首页 Web前端技术论坛

通用于IE和Firefox的getCurrentStyel()

浏览 4487 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2006-11-17  
js 代码
 
  1. function getCurrentStyle(oElement, sProperty) {  
  2.     if (oElement.currentStyle) {  
  3.         return oElement.currentStyle[sProperty];  
  4.     } else if (window.getComputedStyle) {  
  5.         sProperty = sProperty.replace(/([A-Z])/g, "-$1").toLowerCase();  
  6.         return window.getComputedStyle(oElement, null).getPropertyValue(sProperty);  
  7.     } else {  
  8.         return null;  
  9.     }  
  10. }  

参考: window.getComputedStyle()
   发表时间:2006-11-20  
此方法不能正确获取float的值, 因为float是JavaScript的保留字,所以IE中使用styleFloat作为脚本属性名,Firefox使用cssFloat,Opera两者都支持。

另外sProperty参数的大小写也会导致无法正确获取属性值。

参考 Prototype 1.5.0_rc2 的解决方法:
1299 	  getStyle: function(element, style) {
1300 	    element = $(element);
1301 	    var inline = (style == 'float' ?
1302 	      (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat') : style);
1303 	    var value = element.style[inline.camelize()];
1304 	    if (!value) {
1305 	      if (document.defaultView && document.defaultView.getComputedStyle) {
1306 	        var css = document.defaultView.getComputedStyle(element, null);
1307 	        value = css ? css.getPropertyValue(style) : null;
1308 	      } else if (element.currentStyle) {
1309 	        value = element.currentStyle[inline.camelize()];
1310 	      }
1311 	    }
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics