获取元素的最终样式

    看到这样一道微信面试题:用JS代码求出页面上一个元素的最终的background-color,不考虑IE浏览器,不考虑元素float情况。(2017.3.1补充:赛赛同学提醒了我,还要考虑background这个复合属性,情况变得异常复杂了,以下代码是之前的,没有考虑。)

    由于element.style.cssText只能访问到元素内联样式即标签style属性,只能用document.defaultView.getComputedStyle,考虑IE的话可用element.currentStyle,不过element.currentStyle无法用于伪元素而document.defaultView.getComputedStyle可以。如果要考虑元素不可见或者没有设定值的时候,backgroundColor的表现可以认为是其父元素的表现(题目的“不考虑元素float情况”)也是这个意思吧。让我来写写代码:

/**
 * 获取元素自身css属性
 * @param elem 元素
 * @param property 属性名(这里不考虑float)
 * @returns {string} css属性值
 */
function computedStyle(elem, property) {
    if (!elem || !property) {
        return '';
    }
    var style = '';
    if (elem.currentStyle) {
        style = elem.currentStyle[camelize(property)];
    } else if (document.defaultView.getComputedStyle) {
        style = document.defaultView.getComputedStyle(elem, null).getPropertyValue(property);
    }
    return style;
}


/**
 * 将-连接属性名转换为驼峰命名形式
 * @param {string} str -连接字符串
 * @returns {string} 驼峰命名字符串
 */
function camelize(str) {
    return str.replace(/-(\w)/g, function (s, p1) {
        return p1.toUpperCase();
    });
}


/**
 * 在elem获取的背景色是否为最终的背景色
 * @param elem
 * @returns {boolean}
 */
function isFinalBGColor(elem) {
    var bgc = computedStyle(elem, 'background-color');
    return (!!bgc) && (bgc !== 'transparent') && (bgc !== 'rgba(0, 0, 0, 0)') && (computedStyle(elem, 'opacity') !== '0') && (computedStyle(elem, 'visibility') !== 'hidden') && (computedStyle(elem, 'display') !== 'none');
}


/**
 * 获得元素最终的背景色(不考虑半透明叠加颜色的情况)
 * @param elem
 * @returns {string}
 */
function getFinalBGColor(elem) {
    if (isFinalBGColor(elem)){
        return computedStyle(elem, 'background-color');
    }else if (elem!==document.documentElement) {
        return getFinalBGColor(elem.parentNode);
    }
    return '';
}

    经过测试,在通常情况下,以上代码可用。