element.style.backgroundColor 僅返回內聯樣式;計算後的樣式(CSS 類、繼承)需用 getComputedStyle。返回值為 rgb(r, g, b) 或 rgba(...) 格式,需轉換為 #RRGGBB。
/**
* 獲取元素計算樣式中的顏色屬性並轉為 #RRGGBB
* @param {HTMLElement} el - 目標元素
* @param {string} prop - CSS 屬性名,如 'backgroundColor'、'color'
* @returns {string} 十六進制顏色,如 '#ff8800';無法獲取時返回空串
*/
function getHexColor(el, prop) {
if (!el) return '';
var style = window.getComputedStyle ? getComputedStyle(el, null) : el.currentStyle; // IE8-
var rgb = style[prop];
if (!rgb || rgb === 'transparent' || rgb === 'rgba(0, 0, 0, 0)') return '';
// 匹配 rgb(r, g, b) 或 rgba(r, g, b, a)
var match = rgb.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (!match) return rgb; // 已是十六進制或命名色
var r = parseInt(match[1], 10).toString(16).padStart(2, '0');
var g = parseInt(match[2], 10).toString(16).padStart(2, '0');
var b = parseInt(match[3], 10).toString(16).padStart(2, '0');
return '#' + r + g + b;
}
<div id="box" style="color: #88ee22; background-color: #ef8989;">測試文字</div>
<button onclick="alert('背景:' + getHexColor(document.getElementById('box'), 'backgroundColor'))">取背景色</button>
<button onclick="alert('字體:' + getHexColor(document.getElementById('box'), 'color'))">取字體色</button>
transparent 或 rgba(0,0,0,0) 無法轉為十六進制,直接返回原值或空串。red、blue 瀏覽器會自動轉為 rgb(...),上述正則可處理。requestAnimationFrame 批量讀取。現代瀏覽器 getComputedStyle 仍返回 rgb()/rgba(),若需保留原始格式,需解析 CSS 原文(如 CSSStyleSheet.cssRules),屬進階用法,一般場景無需關注。