简体   繁体   English

在PHP / HTML中交替行颜色的最简单方法?

[英]Easiest way to alternate row colors in PHP/HTML?

Here's a PHP example of mine. 这是我的一个PHP示例。 Can anyone find a shorter/easier way to do this? 任何人都可以找到更短/更简单的方法吗?

<? foreach($posts as $post){?>
    <div class="<?=($c++%2==1)?‘odd’:NULL?>">
        <?=$post?>
    </div>
<? }?>

<style>
    .odd{background-color:red;}
</style>

Examples in other languages would be fun to see as well. 其他语言的例子也很有趣。

Fundamentally - no. 从根本上说 - 没有。 That's about as easy as it gets. 这就像它变得一样简单。 You might rewrite it a bit shorter/cleaner, but the idea will be the same. 你可能会把它改写得更短/更干净,但这个想法是一样的。 This is how I would write it: 这是我写它的方式:

$c = true; // Let's not forget to initialize our variables, shall we?
foreach($posts as $post)
    echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>";

If you'd like to have less in-line PHP, a great way of doing it is via JavaScript. 如果你想减少内联PHP,那么一个很好的方法就是通过JavaScript。

Using jQuery, it's simply: 使用jQuery,它很简单:

<script type="text/javascript">
$('div:odd').css('background-color', 'red');
</script>

Using CSS3 you can do something like this: 使用CSS3你可以这样做:

div:nth-child(odd)
{
  background-color: red
}

But better not use that for a few years if you actually want your users to see the color... 但如果您真的希望用户看到颜色,最好不要使用它几年......

Smarty has it inbuilt: Smarty内置它:

{section name=rows loop=$data}
<tr class="{cycle values="odd,even"}">
   <td>{$data[rows]}</td>
</tr>
{/section}

So does Django: Django也是如此:

{% for o in some_list %}
    <tr class="{% cycle 'row1' 'row2' %}">
        ...
    </tr>
{% endfor %}

i always name my zebra rows "row0" and "row1" - this makes the code a bit simpler. 我总是将斑马行命名为“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>';
} 
?>

Maybe a function with a static variable? 也许一个带静态变量的函数?

<?php

function alternate_row_color($css_class) {
    static $show = true;

    $show = !$show;

    if ($show) {
        return $css_class;
    } else {
        return NULL;
    }
}

?>

Then to use it (using your example): 然后使用它(使用你的例子):

<?php foreach($posts as $post) { ?>
    <div class="<?=alternate_row_color('odd')?>">
        <?=$post?>
    </div>
<?php } ?>
<?php $alt = true; foreach ($posts as $post): $alt = !$alt; ?>
<div<?php echo $alt ? ' class="odd"' : ''; ?>>
    <!-- Content --> 
</div>  
<?php endforeach ?>

Would be the simplest and clearest way to do it. 这将是最简单,最清晰的方式。

Just for fun 纯娱乐

Assuming you can use CSS3 selectors you can do something like 假设您可以使用CSS3选择器,您可以执行类似的操作

<div class="posts">
<? foreach($posts as $post){?>
    <div>
        <?=$post?>
    </div>
<? }?>
</div>

<style>
    div.posts div:odd{background-color:red;}
</style>

Even with CSS2 support and mootools (javascript library) you can substitute the style with this javascript 即使有CSS2支持和mootools(javascript库),你也可以用这个javascript替换样式

<script type="text/javascript">
    // obviously this script line should go in a js file in a onload (or onDomReady) function
    $$('div.posts div:odd').setStyle('background-color','red');
</script>

If you don't have anything but php a it you can simplify a bit yous code using an array 如果除了php之外什么都没有,你可以使用数组简化一些代码

<? $isodd=array('','odd');
   $c=0;
   foreach($posts as $post){?>
    <div class="<?=$isodd[$c++%2]?>">
        <?=$post?>
    </div>
<? }?>

You can encapsulate the logic as follows: 您可以按如下方式封装逻辑:

<?php

class ListCycler {
    private $cols, $offs, $len;

    // expects two or more string parameters
    public function __construct() {
        $this->offs = -1;
        $this->len = func_num_args();
        $this->cols = func_get_args();

        foreach($this->cols as &$c)
            $c = trim(strval($c));
    }

    // the object auto-increments every time it is read
    public function __toString() {
        $this->offs = ($this->offs+1) % $this->len;
        return $this->cols[ $this->offs ];
    }
}
?>
<html>
<head>
  <style>
    ul#posts li.odd { background-color:red; }
    ul#posts li.even { background-color:white; }
  </style>
</head>
<body>
  <div>
    <h3>Posts:</h3>
    <ul id="posts"><?php
        $rc = new ListCycler('odd','even');
        foreach($posts as $p)
            echo "<li class='$rc'>$p</li>";
    ?></ul>
  </div>
</body>
</html>

You can abuse the $GLOBAL scope to store the current selected class state, see below table_row_toggle() function. 您可以滥用$ GLOBAL范围来存储当前选定的类状态,请参阅下面的table_row_toggle()函数。 Yes, I know its dirty to abuse the $GLOBAL scope, but hey, we're here to fix problems ain't we? 是的,我知道它肮脏滥用$ GLOBAL范围,但是,嘿,我们来这里解决问题不是吗? :) :)

Calling the table row toggle function in HTML: 在HTML中调用表格行切换功能:

<tr <? table_row_toggle(); ?>>

The function in PHP: PHP中的函数:

/* function to toggle row colors in tables */
function table_row_toggle() {
    /* check if $trclass is defined in caller */
    if(array_key_exists('trclass', $GLOBALS)) {
        $trclass = $GLOBALS['trclass'];
    }   

    /* toggle between row1 and row2 */
    if(!isset($trclass) || $trclass == 'row2') {
        $trclass = 'row1';
    } else {
        $trclass = 'row2';
    }   

    /* set $trclass in caller */
    $GLOBALS['trclass'] = $trclass;

    /* write the desired class to the caller */
    echo ' class="' . $trclass . '"';
}
    <?php   ($i%2==1) ? $bgc='#999999' : $bgc='#FFFFFF'; ?>
    '<div bgcolor=" bgcolor='.$bgc.'">';

在Vilx上发现但是,速度总是很小(页面重量)

<tr class="'.(($c = !$c)?'odd':'even').'">
function row_color($cnt,$even,$odd) { 
echo ($cnt%2) ? "<tr bgcolor=\"$odd\">" : "<tr bgcolor=\"$even\">"; 
} 

How to use: 如何使用:

$cnt=0;
while ($row = mysql_fetch_array ($result)) {
row_color($cnt++,"e0e0e0","FFFFFF");
}

It's short enough as it is, but I would probably wrap it into some helper function with a clear name. 虽然它很短,但我可能会把它包装成一个名字明确的辅助函数。 That way it's more obvious what's going on and you won't have to repeat that logic in all templates where you need it. 这样就可以更明显地发生了什么,你不必在你需要的所有模板中重复那个逻辑。

If you want to do it on the display end and are comfortable with or otherwise already using javascript, libraries like jQuery will often have :odd and :even selectors, which you can then hook up to adding specific style properties or hooking into CSS more generally by adding classes . 如果你想在显示端做到并且习惯使用或者已经使用javascript,jQuery这样的库通常会有:odd:even选择器,然后你可以连接到添加特定样式属性或者更常见地挂钩到CSS通过添加类

On a side noe, to alternate between two values a and b , a nice way of doing it in a loop is this: 在另一方面,要在两个值ab之间交替,在循环中执行此操作的一种好方法是:

x = a;
while ( true ) {
    x = a + b - x;
}

You can also do this without addition and subtraction: 您也可以在没有加法和减法的情况下执行此操作:

x = a ^ b ^ x;

where ^ is the XOR operation. 其中^是XOR操作。

If you just want to alternate between 0 and 1, you can do this: 如果您只想在0和1之间切换,则可以执行以下操作:

x = 0;
while ( true ) {
    x = !x;
}

You could of course use x as an index of colors, CSS style classes and so on. 您当然可以使用x作为颜色索引,CSS样式类等。

In PHP I am using this code: 在PHP中我使用此代码:

function alternate($sEven = "even", $sOdd = "odd")
{
    static $iCount;
    return ($iCount++ & 1) ? $sOdd :$sEven;
}

for($i = 0; $i< 5; $i++)
echo alternate();


/*output:

even
odd
even
odd
even

*/

Source: http://sklueh.de/2013/11/einfache-alternierung-mit-php/ 资料来源: http//sklueh.de/2013/11/einfache-alternierung-mit-php/

Been using something like this: 一直在使用这样的东西:

<?php
function cycle(&$arr) {
    $arr[] = array_shift($arr);
    return end($arr); 
}

$oddEven = array('odd', 'even');
echo cycle($oddEven)."\n";
echo cycle($oddEven)."\n";
echo cycle($oddEven)."\n";

A simple little function that works well for me. 一个适合我的简单小功能。

 <?php 
class alternating_rows()
{
    private $cycler = true;
//------------------------------------------------------------------------------
    function rowclass($row0,$row1)
    {
        $this->cycler = !$this->cycler;//toggle the cycler
        $class=($this->cycler)?$row0:$row1;
        return $class;
    }// end function rowclass
//------------------------------------------------------------------------------    

}//end class alternating rows
?>
<?php $tablerows= new alternating_rows();?>
<table>
  <tr>
    <th scope="col">Heading 1</th>
    <th scope="col">Heading 2</th>
  </tr>
  <?php foreach ($dataset as $row){?>
  <tr class="<?php echo $tablerows->rowclass("oddrow","evenrow"); ?>">
    <td>some data</td>
    <td>some more data</td>
  </tr>
  <?php } //end foreach?>
</table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM