如何将元素的背景颜色设置为该元素的类名的值?

时间:2015-06-30 01:00:15

标签: javascript jquery html css

我想让跨度的类成为使用jQuery的相同跨度的背景颜色。有没有办法这样做?



$(function() {
$("span").css("background-color")
});

span {
  display: inline-block;
  width: 5px;
  height: 5px;
  border: solid #0a0a0a 1px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="red"></span>
<span class="red"></span>
<span class="red"></span>
<span class="blue"></span>
<span class="silver"></span>
<span class="black"></span>
<span class="black"></span>
<span class="silver"></span>
<span class="grey"></span>
<span class="silver"></span>
<span class="green"></span>
<span class="lightgreen"></span>
<span class="gold"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="gold"></span>
<span class="gold"></span>
<span class="gold"></span>
<span class="red"></span>
<span class="red"></span>
<span class="red"></span>
<span class="red"></span>
<span class="green"></span>
<span class="green"></span>
<span class="green"></span>
<span class="green"></span>
<span class="lightgreen"></span>
<span class="lightgreen"></span>
<span class="green"></span>
<span class="green"></span>
<span class="gold"></span>
<span class="gold"></span>
<span class="orange"></span>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:5)

您可以将函数作为第二个参数传递,该参数可以返回类的名称

$(function() {
  $("span").css("background-color", function() {
    return this.className;
  })
});
span {
  display: inline-block;
  width: 5px;
  height: 5px;
  border: solid #0a0a0a 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="red"></span><span class="red"></span><span class="red"></span><span class="blue"></span><span class="silver"></span><span class="black"></span><span class="black"></span><span class="silver"></span><span class="grey"></span><span class="silver"></span>
<span
class="green"></span><span class="lightgreen"></span><span class="gold"></span><span class="yellow"></span><span class="yellow"></span><span class="yellow"></span><span class="yellow"></span><span class="yellow"></span><span class="yellow"></span><span class="gold"></span>
  <span
  class="gold"></span><span class="gold"></span><span class="red"></span><span class="red"></span><span class="red"></span><span class="red"></span><span class="green"></span><span class="green"></span><span class="green"></span><span class="green"></span><span class="lightgreen"></span>
    <span
    class="lightgreen"></span><span class="green"></span><span class="green"></span><span class="gold"></span><span class="gold"></span><span class="orange"></span>