获取对象样式属性函数getStyle()

function getStyle(elem, styleName){  

    if(elem.style[styleName]){ //获取内联样式  

        return elem.style[styleName];  

    }  

    else if(elem.currentStyle){ //IE特有的属性  

        return elem.currentStyle[styleName];  

    }  

    else if(window.getComputedStyle){ //DOM标准属性  

        return window.getComputedStyle(elem, null)[styleName];  

    }  

    else{   

        return null;  

    }  

}  

  

考虑到函数中有重复工作的部分,优化一下:

function getStyle(elem, styleName){  

    if(elem.currentStyle) {  

        getStyle = function(elem, styleName) {  

            if(elem.style[styleName]){   

                return elem.style[styleName];    

            } else {  

                 return elem.currentStyle[styleName];  

            }  

        }  

    } else if(window.getComputedStyle) {  

        getStyle = function(elem, styleName) {  

            if(elem.style[styleName]){  

                return elem.style[styleName];  

            } else {  

                return window.getComputedStyle(elem, null)[styleName];    

            }  

        }  

    } else {  

        getStyle = function(elem, styleName) {  

            return elem.style[styleName];  

        }  

    }  

    return getStyle(elem, styleName);  

}  

  

代码貌似有点长了,再优化一下:

function getStyle(elem, styleName){  

    if(elem.currentStyle) {  

        getStyle = function(elem, styleName) {  

            return elem.style[styleName] ? elem.style[styleName] : elem.currentStyle[styleName];  

        }  

    } else if(window.getComputedStyle) {  

        getStyle = function(elem, styleName) {  

            return elem.style[styleName] ? elem.style[styleName] : window.getComputedStyle(elem, null)[styleName];  

        }  

    } else {  

        getStyle = function(elem, styleName) {  

            return elem.style[styleName];  

        }  

    }  

    return getStyle(elem, styleName);  

}  

 

不作多余代码解释了,网上搜下一大堆。

 

 

你可能感兴趣的:(style)