簡體   English   中英

在PHP / HTML中交替行顏色的最簡單方法?

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

這是我的一個PHP示例。 任何人都可以找到更短/更簡單的方法嗎?

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

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

其他語言的例子也很有趣。

從根本上說 - 沒有。 這就像它變得一樣簡單。 你可能會把它改寫得更短/更干凈,但這個想法是一樣的。 這是我寫它的方式:

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

如果你想減少內聯PHP,那么一個很好的方法就是通過JavaScript。

使用jQuery,它很簡單:

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

使用CSS3你可以這樣做:

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

但如果您真的希望用戶看到顏色,最好不要使用它幾年......

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 %}

我總是將斑馬行命名為“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>';
} 
?>

也許一個帶靜態變量的函數?

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

這將是最簡單,最清晰的方式。

純娛樂

假設您可以使用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之外什么都沒有,你可以使用數組簡化一些代碼

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

您可以按如下方式封裝邏輯:

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

您可以濫用$ 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 . '"';
}
    <?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\">"; 
} 

如何使用:

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

雖然它很短,但我可能會把它包裝成一個名字明確的輔助函數。 這樣就可以更明顯地發生了什么,你不必在你需要的所有模板中重復那個邏輯。

如果你想在顯示端做到並且習慣使用或者已經使用javascript,jQuery這樣的庫通常會有:odd:even選擇器,然后你可以連接到添加特定樣式屬性或者更常見地掛鈎到CSS通過添加類

在另一方面,要在兩個值ab之間交替,在循環中執行此操作的一種好方法是:

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

您也可以在沒有加法和減法的情況下執行此操作:

x = a ^ b ^ x;

其中^是XOR操作。

如果您只想在0和1之間切換,則可以執行以下操作:

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

您當然可以使用x作為顏色索引,CSS樣式類等。

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

一直在使用這樣的東西:

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

一個適合我的簡單小功能。

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