獲取元素的最終樣式

    看到這樣一道微信面試題:用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 '';
}

    經過測試,在通常情況下,以上代碼可用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章