如何以不同的方式动态地将颜色应用于HTML表格? [英] How can I apply dynamically color to each row differently to HTML table?
问题描述
我已经使用javascripts动态创建了HTML表格,现在我想要将每一行应用为不同的颜色。我怎么能这样做?
I've created HTML table dynamically using javascripts and now I want to apply each row a different color. How can I do so?
推荐答案
你可以通过以下方式之一来实现这个目标:css或者javascript:
you can achieve this by one of the following: css OR javascript:
javascript 方法(我建议包含jQuery):
javascript approach (i suggest including jQuery):
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
// paint rows on document ready
$(function(){
paint_rows();
});
function paint_rows() {
$('#table_id tr').each(function(){
$(this).css('color', get_random_color());
});
}
</script>
只需确保在数组中添加足够的颜色值 colors
(也可以使用十六进制值)。
just make sure to add enough color values into the array colors
(can use hex values as well).
并且,你可以调用函数 paint_rows()
当然需要的时候。
and, you can call the function paint_rows()
whenever needed of course.
或者你可以使用 css 方法:
<style type="text/css">
#table_id tr:nth-child(1){color:blue;}
#table_id tr:nth-child(2){color:red;}
#table_id tr:nth-child(3){color:orange;}
/* etc... */
</style>
但我总是喜欢javascript。
but i always prefer javascript.
HOWEVER!
如果您只想为每隔一行着色并在两种颜色之间切换(例如:黑色,一个蓝色,一个黑色,一个蓝色等)使用以下 css :
if you just want to color every second row and switch between two colors (for example: one black, one blue, one black, one blue etc.) use the following css:
#table_id tr{color:black;}
#table_id tr:nth-child(even){color:blue;}
希望有所帮助。
这篇关于如何以不同的方式动态地将颜色应用于HTML表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!