Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP/HTML中交替行颜色的最简单方法?_Php_Html_Css_Colors - Fatal编程技术网

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

在PHP/HTML中交替行颜色的最简单方法?,php,html,css,colors,Php,Html,Css,Colors,下面是我的一个PHP示例。有人能找到一种更短/更简单的方法吗 <? foreach($posts as $post){?> <div class="<?=($c++%2==1)?‘odd’:NULL?>"> <?=$post?> </div> <? }?> <style> .odd{background-color:red;} </style> 基本上-不

下面是我的一个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>";
$c=true;//别忘了初始化变量,好吗?
foreach($posts作为$post)

echo'可能是一个带有静态变量的函数

<?php

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

    $show = !$show;

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

?>

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



虽然它很短,但我可能会将它包装成一个有明确名称的助手函数。这样一来,情况就更为明显,您不必在所有需要的模板中重复该逻辑。


<?php $alt = true; foreach ($posts as $post): $alt = !$alt; ?>
<div<?php echo $alt ? ' class="odd"' : ''; ?>>
    <!-- Content --> 
</div>  
<?php endforeach ?>
这是最简单、最清晰的方法。

Smarty内置了:

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

{% for o in some_list %}
    <tr class="{% cycle 'row1' 'row2' %}">
        ...
    </tr>
{% endfor %}
{%for o在某些\u列表%}
...
{%endfor%}

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

div:nth-child(odd)
{
  background-color: red
}
<?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";

但是,如果你真的想让用户看到颜色,最好在几年内不要使用它…

如果你想在显示端使用它,并且对javascript感到满意,或者已经在使用javascript,像jQuery这样的库通常会有和选择器,然后,您可以通过以下方式将其连接到CSS中:添加特定的或更一般地连接到CSS中。

如果您希望减少内嵌式PHP,一个很好的方法是通过JavaScript

使用jQuery,只需:

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

$('div:odd').css('background-color','red');
只是为了好玩

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

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

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

div.posts div:odd{背景色:红色;}
即使使用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>

//显然,这个脚本行应该放在onload(或onDomReady)函数的js文件中
$$('div.posts div:odd').setStyle('background-color','red');
如果你除了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>

ul#posts li.odd{背景色:红色;}
ul#posts li.偶数{背景色:白色;}
帖子:

在noe侧,要在两个值a和b之间交替,在循环中执行此操作的一个好方法是:

x = a;
while ( true ) {
    x = a + b - x;
}
您也可以在不使用加减法的情况下执行此操作:

x = a ^ b ^ x;
其中^是异或运算

如果只想在0和1之间切换,可以执行以下操作:

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

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

一直在使用这样的东西:

div:nth-child(odd)
{
  background-color: red
}
<?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";

我总是将斑马行命名为“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 
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> 

标题1
标题2

可以滥用$GLOBAL作用域来存储当前选定的类状态,请参见下表\u row\u toggle()函数。是的,我知道滥用$GLOBAL范围是肮脏的,但是,嘿,我们是来解决问题的,不是吗?:)

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

<tr <? table_row_toggle(); ?>>

'';

在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

*/
功能替代($sEven=”偶数“,$sOdd=”奇数”)
{
静态$iCount;
返回($iCount++&1)$sOdd:$7;
}
对于($i=0;$i<5;$i++)
回声交替();
/*输出:
即使
古怪的
即使
古怪的
即使
*/

来源:

在Vilx上定位,但速度(页面重量)始终保持最低




您只需定义一次函数,然后在您想要使用它的任何地方对函数进行一次非常简短且可读性很强的调用。这似乎是一个很好的示例,但对于这些基础知识来说,只要有一个代码片段,您就可以随时将其插入。乍一看,静态可能很难阅读/理解。OP中的成语更容易理解。此外,如果您同时有多个内容交替(例如,行和列会以奇数列分隔),这也不起作用。与@Vilx(之前发布过)几乎相同,但仍然是一个好的。我不使用jQuery,但这看起来是一个很好的、干净的代码。别忘了!如果您使用Javascript解决方案(jquery、prototype或其他任何东西),当页面加载时,您将有一个小的flick。事实上,在页面完全加载之前,您的行上不会有“斑马”。对一些人来说,这可能是个问题。我也支持这一点。使奇数单元格具有不同的颜色是一个设计问题,因此最好在JS或CSS中处理,而不是在业务逻辑(PHP)中处理。@Bob:这里的PHP正在打印HTML,这是表示逻辑的一部分。PHP或CSS3在这方面比javascript好得多,没有回流,没有F.O.U.C不应该是uu toString()?为什么是trim()?这使得这个类变得不那么有用。您对“simpler”nickf有一个非常奇怪的想法:(grin)很明显,您只编写了一次ListCycler类,并将其存储在库代码中。当你使用它时,它是非常简单的-创建一个ListCycle对象,然后重复调用它,所有的逻辑都是隐藏的。请不要使用短的开放标记(例如,哇!这似乎是有史以来最短的一个!@thrashr:if you
foreach($i=>$row的行)
您可以删除
$i=0
。但所有这一切都取决于在对行进行foreach之前将行作为一个数组。为此,它工作得非常好。下面是我将其更改为在两个TR类(奇数和偶数)之间交替使用的内容谢谢你的解决方案!太好了!这将在第一次迭代时生成一个警告,因为$c未初始化,而且当你应该引用“$c”时,你正在引用“c”,这将生成错误或警告,或无效行为。记不清是哪一个。@Brian Cline:谢谢你的评论。根据编辑了这篇文章;但事实并非如此不
/* 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.'">';
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

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