jQuery的设置元素的背景颜色根据其值
问题描述:
我要的是这样的:jQuery的设置元素的背景颜色根据其值
<script>
$(document).ready(function(){
$(".colored").css("background-color", "rgb(255, 100 + $(this).val(), 0)");
});
</script>
的目标是类中的“彩色”的元素将被着色根据每个元素的值。我怎样才能使它工作?谢谢。
答
您可以使用$.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">
答
尝试以下
代码<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>
答
使用此,假设你的HTML元素DIV,如果是文本框使用$(这).VAL()而不是$(本)的.text()
$(".colored").each(function(i){
var shaded = 100 + parseInt($(this).text());
$(this).css("background-color", "rgb(255, "+shaed+", 0)");
})
工作就像一个魅力! – user3925803