-1

我需要动态设置页面的“随机”背景颜色。是否有任何 php 函数来生成可以提供帮助的十六进制颜色代码或片段。

4

4 回答 4

2

没有PHP内置函数

$rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
$color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];

然后在您需要的任何地方回显 $color 值。

于 2013-10-30T07:46:25.213 回答
0

你可以试试这个

     <?php


         /**
         * Get random color hex value
         *
         * @param  int $max_r Maximum value for the red color
         * @param  int $max_g Maximum value for the green color
         * @param  int $max_b Maximum value for the blue color
         * @return string
         */

       echo getRandomColorHex();

       function getRandomColorHex($max_r = 255, $max_g = 255, $max_b = 255)
       {
          // ensure that values are in the range between 0 and 255
          $max_r = max(0, min($max_r, 255));
          $max_g = max(0, min($max_g, 255));
          $max_b = max(0, min($max_b, 255));

          // generate and return the random color
          return str_pad(dechex(rand(0, $max_r)), 2, '0', STR_PAD_LEFT) .
                 str_pad(dechex(rand(0, $max_g)), 2, '0', STR_PAD_LEFT) .
                 str_pad(dechex(rand(0, $max_b)), 2, '0', STR_PAD_LEFT);
        }
于 2013-10-30T07:47:09.010 回答
0
$random_color = dechex(rand(0,255*255*255));
于 2013-10-30T08:46:48.363 回答
0
sprintf('%06x', mt_rand(0, 1<<24 - 1));

红色、绿色和蓝色的颜色是 8 位,因此我们选择一个随机的 24 位数字。然后我们 0-pad 并将其打印为十六进制。

于 2013-10-30T08:06:09.007 回答