【问题标题】:How to set contents to background color?如何将内容设置为背景颜色?
【发布时间】:2014-11-15 05:16:14
【问题描述】:
我有一张表格,里面有各种动态生成的背景颜色。我想使用 jQuery 用单元格的实际背景颜色填充表格单元格内容。我可以使用$("td").text("new contents"); 来更改单元格的内容。我尝试$("td").text($(this).css("backgroundColor"));将背景色放入单元格,但背景色没有通过。
$("td").text(
$(this).css("backgroundColor")
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>lighten</td>
<td style="background-color: #d379a6;">10%</td>
<td style="background-color: white;">50%</td>
<td style="background-color: white;">100%</td>
</tr>
<tr>
<td>darken</td>
<td style="background-color: #ad3972;">10%</td>
<td style="background-color: #14060d;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
<tr>
<td>mix</td>
<td style="background-color: #b24a7e;">10%</td>
<td style="background-color: #632946;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
</table>
【问题讨论】:
标签:
javascript
jquery
css
【解决方案1】:
试试这个:
$("td").text(function() {
return $(this).css("backgroundColor");
});
.text 方法可以将函数作为参数。在这种情况下,此函数必须返回值以用作集合中元素的新文本内容。
您的版本$("td").text($(this).css("backgroundColor")); 不正确,因为在这种情况下this 指向全局对象(即window 对象),显然$(this).css("backgroundColor") 不返回任何内容。
$("td").text(function() {
return $(this).css("backgroundColor");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>lighten</td>
<td style="background-color: #d379a6;">10%</td>
<td style="background-color: white;">50%</td>
<td style="background-color: white;">100%</td>
</tr>
<tr>
<td>darken</td>
<td style="background-color: #ad3972;">10%</td>
<td style="background-color: #14060d;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
<tr>
<td>mix</td>
<td style="background-color: #b24a7e;">10%</td>
<td style="background-color: #632946;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
</table>
【解决方案2】:
接受的答案解决了我遇到的问题,但我还希望颜色以十六进制显示,这不是 jQuery 返回的内容。所以我从Can I force jQuery.css("backgroundColor") returns on hexadecimal format? 移植了一个解决方案。这是我最终实现的最后一个 jQuery:
$("td").text(function() {
color = $(this).css("backgroundColor");
bg = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
});