thr*_*888 26 html css php colors
这是我的一个PHP示例.任何人都可以找到更短/更简单的方法吗?
<? foreach($posts as $post){?>
<div class="<?=($c++%2==1)?‘odd’:NULL?>">
<?=$post?>
</div>
<? }?>
<style>
.odd{background-color:red;}
</style>
Run Code Online (Sandbox Code Playgroud)
其他语言的例子也很有趣.
Vil*_*lx- 46
从根本上说 - 没有.这就像它变得一样简单.你可能会把它改写得更短/更干净,但这个想法是一样的.这是我写它的方式:
$c = true; // Let's not forget to initialize our variables, shall we?
foreach($posts as $post)
echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>";
Run Code Online (Sandbox Code Playgroud)
Max*_*Max 19
如果您希望使用较少的内嵌PHP,那么通过JavaScript可以很好地实现这一目标.
使用jQuery,它很简单:
<script type="text/javascript">
$('div:odd').css('background-color', 'red');
</script>
Run Code Online (Sandbox Code Playgroud)
Ole*_*sen 11
使用CSS3你可以这样做:
div:nth-child(odd)
{
background-color: red
}
Run Code Online (Sandbox Code Playgroud)
但如果您真的希望用户看到颜色,最好不要使用它几年......
Smarty内置它:
{section name=rows loop=$data}
<tr class="{cycle values="odd,even"}">
<td>{$data[rows]}</td>
</tr>
{/section}
Run Code Online (Sandbox Code Playgroud)
Django也是如此:
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我总是将斑马行命名为"row0"和"row1" - 这使得代码更简单一些.
<?php // you should always use the full opening tag for compatibility
$i = 0;
foreach ($rows as $row) {
echo '<tr class="row' . ($i++ % 2) . '">...</tr>';
}
?>
Run Code Online (Sandbox Code Playgroud)