这是一种更强大的方法:DEMO
注意: bgColor 已被弃用。您应该在style 属性上使用background-color 属性。此外,仅注册 click 事件也不是跨浏览器友好的。
JavaScript
function addEventHandler(elem, eventType, handler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, handler, false); // IE < 9 :(
} else if (elem.attachEvent) {
elem.attachEvent('on' + eventType, handler);
}
}
function getStyle(elem, prop) {
if (elem.currentStyle)
return elem.currentStyle[prop];
else if (window.getComputedStyle){
var elStyle = window.getComputedStyle(elem, "");
return elStyle.getPropertyValue(prop);
}
}
function toHex(c) {
var hex = parseInt(c).toString(16).toUpperCase();
return hex.length == 1 ? "0" + hex : hex;
}
function rgb2Hex(rgbStr) {
var rgbArr = rgbStr.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
return '#' + toHex(rgbArr[1]) + toHex(rgbArr[2]) + toHex(rgbArr[3]);
}
var input = document.getElementById('txt');
var table = document.getElementById('color_table');
addEventHandler(table, 'click', getColor);
function getColor(e) {
var target = e.target;
if (target.tagName === 'TD') {
input.value = rgb2Hex(getStyle(target, 'background-color'));
}
}
HTML
<label for="txt">Selected Color Value</label>
<input id="txt" type="text" />
<br />
<table id="color_table">
<thead>
<tr>
<th>Red</th>
<th>Green</th>
<th>Blue</th>
</tr>
</thead>
<tbody>
<tr>
<td class="r1"></td>
<td class="g1"></td>
<td class="b1"></td>
</tr>
<tr>
<td class="r2"></td>
<td class="g2"></td>
<td class="b2"></td>
</tr>
<tr>
<td class="r3"></td>
<td class="g3"></td>
<td class="b3"></td>
</tr>
</tbody>
</table>
样式表
table { border: thin black solid; }
td { width: 20px; height: 20px; }
.r1 { background: #FF0000; }
.r2 { background: #CF0000; }
.r3 { background: #7F0000; }
.g1 { background: #00FF00; }
.g2 { background: #00CF00; }
.g3 { background: #007F00; }
.b1 { background: #0000FF; }
.b2 { background: #0000CF; }
.b3 { background: #00007F; }