开发者

Random Font Colors

I need to color text with 2 or 3 random colors. 开发者_开发知识库 How can I do this in PHP or JavaScript?


$color = str_pad(sprintf("%x%x%x", rand(0,255), rand(0,255), rand(0,255)),6,rand(0,9));
echo '<span style="color:'.$color.'">Random Color</span>';

Provides random #<Red><green><blue> color


This should do the trick:

function getRandomColour() {
    return 'red';      // chosen by fair dice roll
                       // guaranteed to be random
}

Courtesy of XKCD, for those of you who are new around here.


<?php
$array = Array('green', 'red', 'blue');
$rand = array_rand($array);
echo $array[$rand]; // This is your random color that you can use in your html


<?php
$color = array(
    1 => "red",
    2 => "blue",
    3 => "green"
); 

echo '<font color="'.$color[rand(1,3)].'">RANDOM TEXT</font>';
echo '<font color="'.$color[rand(1,3)].'">RANDOM TEXT</font>';
echo '<font color="'.$color[rand(1,3)].'">RANDOM TEXT</font>';

?>


echo $colors[ rand()%count($colors) ];

1 line of code ftw


$colors = array();

foreach (range(1, 3) as $i)
{
    foreach (array('red', 'green', 'blue') as $color)
    {
        $colors[$i][$color] = mt_rand(0, 255);
    }
}

echo '<pre>';
print_r($colors);
echo '</pre>';

Output:

Array
(
    [1] => Array
        (
            [red] => 101
            [green] => 227
            [blue] => 175
        )

    [2] => Array
        (
            [red] => 78
            [green] => 82
            [blue] => 161
        )

    [3] => Array
        (
            [red] => 215
            [green] => 237
            [blue] => 135
        )
)


function getRandomColor() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 15)];
        }
        return color;
    }

This can be used for text and backgrounds. You can view it working in a div here by clicking the button: http://sweb1.dmit.nait.ca/~bkoepke1/Random%20Colour%20Generator/


you can put php code in your css files as well:

<?php
    header("Content-type: text/css");
?>

.color1 {
    background-color: <?php echo get_rand_color_code(); ?>;
}

.color2 {
    background-color: <?php echo get_rand_color_code(); ?>;
}

.color3 {
    background-color: <?php echo get_rand_color_code(); ?>;
}

the function get_rand_color_code() you'll have to do by yourself. it just have to return a random code like "#afb3e4"

the header in the begining of the file allows it to be called as a css by your html. you should name and call it as a .php file.

<link rel="stylesheet" href="style.php" />

this is ONE example of how you can do it (:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜