Numbers & css classes
How can I add a css class to a randomly generated numb开发者_Go百科er.
example:
if the number is under 2000 add a css class named red to the div <div class="red">500</div>
if the number is over 2000 add a css class named blue to the div <div class="blue">2500</div>
There are many ways this could be done, but here's one simple one. If $rNum
holds your randomly-generated number we can test whether it is less than or equal to 2000. If it is, we'll print "red", and if it's not we'll print "blue".
<p class="<?php print ( $rNum <= 2000 ) ? "red" : "blue" ; ?>">Hello World</p>
If you're new to PHP you may find the syntax of the ternary operator to be somewhat confusion. It's basically a simplified inline if-else statement. You can see more examples and read a short description online at php.net.
you can first generate the rand number, store it into a variable and then use if..else
to add the class to div element, like below:
<?php $rand = rand($min,$max); ?>
<div class="<?php if ( $rand <= 2000 ) echo "red"; else echo "blue" ; ?>"><?php echo $rand; ?></div>
Alternatively, add an id
element to this div tag, and then use Javascript to add the class.
Do you want to do this?
<div class="<?php echo ($number<2000)?'red':'blue'; ?>">
<?php echo $number ?>
</div>
精彩评论