萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 取得元素計算後背景色與字體顏色並轉為十六進制格式

核心問題

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'));

互動 Demo

<!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 + 正則解析,健壯且標準。

copyright © 萬盛學電腦網 all rights reserved