【问题标题】:Easiest way to alternate row colors in PHP/HTML?在 PHP/HTML 中交替行颜色的最简单方法?
【发布时间】:2010-09-28 18:53:27
【问题描述】:

这是我的一个 PHP 示例。任何人都可以找到更短/更简单的方法吗?

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

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

其他语言的示例也很有趣。

【问题讨论】:

  • 请不要使用短的开放标签(即 ) - 它不能在所有配置中移植。

标签: php html css colors


【解决方案1】:

基本上 - 不。这很容易。您可能会将它改写得更短/更清晰,但想法是一样的。我就是这样写的:

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

【讨论】:

  • 感谢您,完美运行。这是我将其更改为在两个 TR 类(奇数和偶数)之间交替的内容 "; ?>
  • 感谢您的解决方案!太好了!
【解决方案2】:

也许是一个带有静态变量的函数?

<?php

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

    $show = !$show;

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

?>

然后使用它(使用您的示例):

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

【讨论】:

  • 您只需定义一次函数,然后在您想使用它的任何地方对函数进行简短且非常易读的调用。
  • 这似乎是一个很好的例子,但对于这些基础知识来说,有一个 sn-p 似乎很不错,只要它弹出就可以扔进去。
  • 静态数据乍一看可能难以阅读/理解。 OP中的成语更好理解。此外,如果您同时有多个交替的事物(例如,行然后列会因奇数列而中断),这也不起作用。
【解决方案3】:

它已经足够短了,但我可能会将它包装到一些具有明确名称的辅助函数中。这样一来,发生的事情就更明显了,您不必在所有需要的模板中重复该逻辑。

【讨论】:

    【解决方案4】:
    <?php $alt = true; foreach ($posts as $post): $alt = !$alt; ?>
    <div<?php echo $alt ? ' class="odd"' : ''; ?>>
        <!-- Content --> 
    </div>  
    <?php endforeach ?>
    

    这将是最简单、最清晰的方法。

    【讨论】:

    • 与@Vilx-(之前发布的)几乎相同,但仍然不错。
    【解决方案5】:

    Smarty 已内置:

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

    Django 也是如此:

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

    【讨论】:

    • 在 Rails 中: ...
    【解决方案6】:

    使用 CSS3,您可以执行以下操作:

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

    但如果您真的希望您的用户看到颜色,最好不要使用几年...

    【讨论】:

      【解决方案7】:

      如果您想在显示端执行此操作并且熟悉或已经在使用 javascript,像 jQuery 这样的库通常会有 :odd:even 选择器,然后您可以连接到添加特定的 style properties或者通过adding classes 更普遍地连接到 CSS。

      【讨论】:

        【解决方案8】:

        如果您希望使用更少的内联 PHP,一个很好的方法是通过 JavaScript。

        使用jQuery,很简单:

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

        【讨论】:

        • 我不使用 jQuery,但这看起来是一段不错的、干净的代码。
        • 别忘了!如果您使用 Javascript 解决方案(jquery、原型或其他任何东西),您将在页面加载时轻弹一下。事实上,在页面完全加载之前,您的行上不会出现“Zebra”。对于某些人来说,这可能是个问题。
        • 我也支持这个。将奇数单元格设置为不同的颜色是设计问题,因此最好在 JS 或 CSS 中处理,而不是在业务逻辑 (PHP) 中处理。
        • @Bob:这里的 PHP 正在打印 HTML,它是表示逻辑的一部分。
        • PHP 或 CSS3 是比 javascript 更好的方法,没有回流也没有 F.O.U.C.
        【解决方案9】:

        只是为了好玩

        假设您可以使用 CSS3 选择器,您可以执行类似的操作

        <div class="posts">
        <? foreach($posts as $post){?>
            <div>
                <?=$post?>
            </div>
        <? }?>
        </div>
        
        <style>
            div.posts div:odd{background-color:red;}
        </style>
        

        即使有 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>
        

        如果您除了 php a 它什么都没有,您可以使用数组简化代码

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

        【讨论】:

        • 这将在第一次迭代时生成警告,因为 $c 未初始化,并且当您应该引用 '$c' 时,您正在引用 'c',这将生成错误或警告,或无效的行为。不记得是哪个了。
        • @Brian Cline:感谢您的评论。根据编辑帖子;
        【解决方案10】:

        可以将逻辑封装如下:

        <?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>
        

        【讨论】:

        • 应该 __get() 不是 __toString() 吗?
        • 为什么是 trim()?这会降低类的可用性。
        • 哇。你对“更简单”有一个非常非常奇怪的想法
        • nickf:(咧嘴笑)好吧,显然您编写了一次 ListCycler 类并将其存储在您的库代码中。当你使用它时,很简单——创建一个ListCycler对象然后重复调用它,所有的逻辑都被隐藏了。
        【解决方案11】:

        另一方面,要在两个值 ab 之间交替,在循环中执行此操作的好方法是:

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

        你也可以不加减法做到这一点:

        x = a ^ b ^ x;
        

        其中 ^ 是 XOR 操作。

        如果你只想在 0 和 1 之间交替,你可以这样做:

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

        您当然可以使用 x 作为颜色、CSS 样式类等的索引。

        【讨论】:

          【解决方案12】:

          一直在使用这样的东西:

          <?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";
          

          【讨论】:

            【解决方案13】:

            我总是将我的斑马行命名为“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>';
            } 
            ?>
            

            【讨论】:

            • 哇!这似乎是有史以来最短的!
            • @thrashr :如果你是foreach ($rows as $i =&gt; $row),你可以删除$i = 0。但这一切都取决于在你可以遍历它们之前将你的行作为一个数组。
            【解决方案14】:
            function row_color($cnt,$even,$odd) { 
            echo ($cnt%2) ? "<tr bgcolor=\"$odd\">" : "<tr bgcolor=\"$even\">"; 
            } 
            

            使用方法:

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

            【讨论】:

              【解决方案15】:

              一个对我很有效的简单小功能。

               <?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> 
              

              【讨论】:

              • 但它并没有更短,当然也不会更容易!但我想它工作得很好。
              【解决方案16】:

              您可以滥用 $GLOBAL 范围来存储当前选定的类状态,请参见下面的 table_row_toggle() 函数。是的,我知道滥用 $GLOBAL 范围很脏,但是,嘿,我们是来解决问题的,不是吗? :)

              在 HTML 中调用表格行切换函数:

              <tr <? table_row_toggle(); ?>>
              

              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 . '"';
              }
              

              【讨论】:

                【解决方案17】:
                    <?php   ($i%2==1) ? $bgc='#999999' : $bgc='#FFFFFF'; ?>
                    '<div bgcolor=" bgcolor='.$bgc.'">';
                

                【讨论】:

                  【解决方案18】:

                  在 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
                  
                  */
                  

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

                  【讨论】:

                    【解决方案19】:

                    在 Vilx 上发现,但总是尽量减少速度(页面重量)

                    <tr class="'.(($c = !$c)?'odd':'even').'">
                    

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2011-10-07
                      • 2011-02-25
                      • 2012-04-18
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多