element.style.backgroundColor 僅回傳**內嵌樣式** 設定的值。外部 CSS、繼承、計算值需用 getComputedStyle。且瀏覽器回傳 rgb(r, g, b) 或 rgba(...),需轉換為 #rrggbb。
/**
* 取得元素計算後的顏色並轉為 #RRGGBB 格式
* @param {Element} el
* @param {'backgroundColor'|'color'|'borderColor'} prop
* @returns {string} #rrggbb 或 'transparent'
*/
function getHexColor(el, prop = 'backgroundColor') {
const style = window.getComputedStyle(el);
const color = style[prop]; // "rgb(255, 0, 0)" 或 "rgba(0,0,0,0)"
// 透明處理
if (color === 'transparent' || color === 'rgba(0, 0, 0, 0)') return 'transparent';
// 解析 rgb/rgba
const match = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (!match) return color; // 已是關鍵字或其他格式
const [, r, g, b] = match.map(Number);
const toHex = n => n.toString(16).padStart(2, '0');
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
// 使用
const box = document.getElementById('colorBox');
console.log('背景色:', getHexColor(box, 'backgroundColor'));
console.log('字體色:', getHexColor(box, 'color'));
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#colorBox { width: 200px; height: 100px; background: #ef8989; color: #88ee22; display: flex; align-items: center; justify-content: center; font-weight: bold; }
</style>
</head>
<body>
<div id="colorBox">測試區塊</div>
<button onclick="alert('背景:'+getHexColor(colorBox,'backgroundColor')+' 字體:'+getHexColor(colorBox,'color'))">取得顏色</button>
<script> /* 上方 getHexColor 函式 */ </script>
</body>
</html>
style.backgroundColor 只讀 inline style;必須用 getComputedStyle。background、border 等簡寫在 computed style 中可能回傳空字串,請用長屬性名(backgroundColor、borderTopColor)。rgba 轉 #rrggbb 會捨棄 alpha;若需保留透明度,回傳 #rrggbbaa(8 位)或保留 rgba() 字串。getComputedStyle 觸發強制佈局,避免在動畫迴圈大量呼叫。原文使用 element.style.backgroundColor.split('(') 僅能處理 inline style,且字串切割脆弱(不支援 rgba、空白變化、關鍵字色)。現代寫法採用 getComputedStyle + 正則解析,健壯且標準。