2013-08-31 33 views
0

比方说,我有一个看起来像这样的代码:如何在while循环中交替使用DIV颜色?

while ($info = mysql_fetch_assoc($data_p)) { 
    $name = stripslashes($info['name']); 
    $desc = stripslashes($info['description']); 
    $desc = substr($desc, 0, 150); 
    $price = stripslashes($info['price']); 
    Print "<div style=\"width:600px; height:150px; border:1px solid black; overflow:hidden\"><div style=\"height:148px; width:25%; border:1px solid red; float:left\"><center><img src=\"".$picture."\" height=\"120\" width=\"120\" style=\"margin-top:15px\" /></center></div><div style=\"height:150px; width:50%; border:1px solid blue; float:left; text-overflow: ellipsis; padding-top:5px\"><center><font size=\"+1\"><b><a href=\"result.php?product=".urlencode($name)."\">".$name."</b></a></font><br><br>".$desc."...</center></div><div style=\"height:150px; width:24%; border:1px solid green; float:left\"><center><h1>$".$price."</h1><button>Add to Cart</button></center></div></div>"; 

中首先while循环定义我想交替的灰色两种色调主要DIV。所以在结果中,它看起来像是浅黑暗的光线暗等......我试着用不同的颜色再次重复回声,但是这会使每个结果重复。有没有办法做到这一点?

+0

我会在while循环之外有一个变量来跟踪这个。然后在循环中,你可以说'$ color =!$ color'或类似的东西来回切换。 –

回答

1
$c = 1; 

while ($info = mysql_fetch_assoc($data_p)) { 
    $name = stripslashes($info['name']); 
    $desc = stripslashes($info['description']); 
    $desc = substr($desc, 0, 150); 
    $price = stripslashes($info['price']); 
    Print "<div style=\"background:" . ($c ? '#ccc' : '#aaa') . "width:600px; height:150px; border:1px solid black; overflow:hidden\"><div style=\"height:148px; width:25%; border:1px solid red; float:left\"><center><img src=\"".$picture."\" height=\"120\" width=\"120\" style=\"margin-top:15px\" /></center></div><div style=\"height:150px; width:50%; border:1px solid blue; float:left; text-overflow: ellipsis; padding-top:5px\"><center><font size=\"+1\"><b><a href=\"result.php?product=".urlencode($name)."\">".$name."</b></a></font><br><br>".$desc."...</center></div><div style=\"height:150px; width:24%; border:1px solid green; float:left\"><center><h1>$".$price."</h1><button>Add to Cart</button></center></div></div>"; 

    $c = 1 - $c; 
1

如果你要保持你的设计和逻辑分离,你可以用CSS做得一样好:

div:nth-child(odd) { 
    background:#c0c0c0; 
} 
div:nth-child(even) { 
    background:#a0a0a0; 
} 
+0

@ user2566387这是专业级的答案。不要混淆你的PHP代码分配样式。按照预期使用css的优雅。 – mickmackusa

1

你可以指望的DIV的数量和颜色改变奇数和偶数。

$num = 0; 
while ($info = mysql_fetch_assoc($data_p)) { 
$num++; 
$color = ($num % 2) ? '#ccc;' : '#aaa'; 
//***insert your relevant variables 
}