JavaScript获取最终的CSS样式属性值

       如果没有在页面标签的style里面显示的设置属性值,那么使用obj.style.属性 会获取不到值,这时候如果需要获取默认值的时候则需要下面的代码帮助获取,以下对IE和其他浏览器做了不同的处理。

 

/** OBJ 需要获取属性的元素,prop 属性名 **/
function GetCurrentStyle(obj, prop){
    if (obj.currentStyle) //IE
    {
        return obj.currentStyle[prop];
    }
    else 
        if (window.getComputedStyle) //非IE
        {
            propprop = prop.replace(/([A-Z])/g, "-$1");
            propprop = prop.toLowerCase();
            return document.defaultView.getComputedStyle(obj, null)[propprop];
        }
    return null;
}

 

如果要得到元素的最终css样式值:可以通过下面这个通用函数得到:

/** 得到元素的最终css样式值 **/
function getStyle(elem,name)
{
    if(elem.style[name])
        return elem.style[name];
    else if(elem.currentStyle)
    {
        return elem.currentStyle[name];
        
    }
    else if(document.defaultView&&document.defaultView.getComputedStyle)
    {
        name=name.replace(/[A-Z]/g,"-$1");
        name=name.toLowerCase();
        var s=document.defaultView.getComputedStyle(elem,"");
        return s&&s.getPropertyValue(name);
        
    }
    else{
        return null;
    }
}    

 

  

posted @ 2013-11-12 09:40  浮生如斯  阅读(436)  评论(0编辑  收藏  举报