【发布时间】:2012-07-12 10:05:04
【问题描述】:
我意识到这类问题已经有好几个主题了,但似乎没有一个与我的匹配。我有正确显示 CSS 背景的一系列 6 个数字的代码。然后将这 6 个数字存储到一个数组中,并将该数组的内容与前面的“#”符号连接起来。然后将其存储为另一个变量。这里:
$v = 0;
$array = array();
$tot;
$other0 = null;
$other1 = null;
$other2 = null;
$other3 = null;
$other4 = null;
$other5 = null;
$color;
for ($i=0;$i<6;$i++){ //loops 6 times to create 5 numbers
$tot = rand(0, 15);
if (($tot>9) && ($tot<16)){ //assigns 10 to "a" in hex
if ($tot == 10){
$tot = $other0;
$other0 = "a";
//echo $other0;
$array[$v++] = $other0;
}
elseif ($tot == 11){ //assigns 11 to "b" in hex
$tot = $other1;
$other1 = "b";
//echo $other1;
$array[$v++] = $other1;
}
elseif ($tot == 12){ //assigns 12 to "b" in hex
$tot = $other2;
$other2 = "c";
//echo $other2;
$array[$v++] = $other2;
}
elseif ($tot == 13){ //assigns 13 to "b" in hex
$tot = $other3;
$other3 = "d";
//echo $other3;
$array[$v++] = $other3;
}
elseif ($tot == 14){ //assigns 14 to "b" in hex
$tot = $other4;
$other4 = "e";
//echo $other4;
$array[$v++] = $other4;
}
elseif ($tot == 15) { //assigns 15 to "b" in hex
$tot = $other5;
$other5 = "f";
//echo $other5;
$array[$v++] = $other5;
}
}
else {
//echo $tot;
$array[$v++] = $tot; //if not, then just assign to array
}
}
$var = "";
$color = "";
for ($t=0; $t<6;$t++){
$var .= (string) $array[$t]; //displays the 6 numbers as one string
}
//var_dump($var); //for more visual reference, uncomment the var_dump
$color = "#" . $var;
echo $color;
以上是PHP。
如何使用 CSS 显示该变量?是不是像(在同一个 PHP 文件中):echo "<style>color:$color</style>";
还是我必须创建一个 style.php 才能被引用?如果我这样做,我该怎么做?
非常感谢!
【问题讨论】:
-
您需要在 html 中的 body 标记之前运行 php。然后你可以在页面中为
body { background-color:<?PHP echo $color; ?> }做一个内联样式 -
你真的需要学习十六进制 :) 查看:php.net/manual/en/function.dechex.php
-
天哪,我这辈子都去哪儿了?
-
@ChaseYuan 记住这一点:无论你想做什么,PHP 都有相应的功能。
-
我建议使用 0 到 255 之间的 3 个随机生成的值,例如: $blub = "#".dechex(mt_rand(0, 255)).dechex(mt_rand(0, 255) ).dechex(mt_rand(0, 255));