2017-06-15 82 views
0

我要的是這樣的:jQuery的設置元素的背景顏色根據其值

<script> 
    $(document).ready(function(){ 
     $(".colored").css("background-color", "rgb(255, 100 + $(this).val(), 0)"); 
    }); 
</script> 

的目標是類中的「彩色」的元素將被着色根據每個元素的值。我怎樣才能使它工作?謝謝。

回答

2

您可以使用$.each()$.text()來遍歷它們並將文本內容值應用爲背景色的一部分。

$('.colored').each(function() { 
 
    $(this).css('background-color','rgb(255,' + (100 + parseInt($(this).text())) + ',0)'); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="colored">50</div> 
 
<div class="colored">100</div> 
 
<div class="colored">130</div>

或承擔這些都是input標籤,你可以使用$.val()

$('.colored').each(function() { 
 
    $(this).css('background-color','rgb(255,' + (100 + parseInt($(this).val())) + ',0)'); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="colored" value="50"> 
 
<input type="text" class="colored" value="100"> 
 
<input type="text" class="colored" value="130">

+1

工作就像一個魅力! – user3925803

0

嘗試以下

代碼
<script> 
    $(document).ready(function(){ 
     $(".colored").each(function(){ 
      $(this).css("background-color", $(this).val()); //Will only work for form elements that support val() function 
      // alternatively you could add a data-color="red" kind of attribute to explicitly set color for all elements 
      // $(this).css("background-color", $(this).data("color")); 
     })   
    }); 
</script> 
0

使用此,假設你的HTML元素DIV,如果是文本框使用$(這).VAL()而不是$(本)的.text()

$(".colored").each(function(i){ 
    var shaded = 100 + parseInt($(this).text()); 
     $(this).css("background-color", "rgb(255, "+shaed+", 0)"); 
    }) 
相關問題