看到這樣一道微信面試題:用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 '';
} 經過測試,在通常情況下,以上代碼可用。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。