When I wanted to do a random replacement of the background image, written in JavaScript, the program flow should be: Create an array of images, a random selection of one of the values, create a style and write to the body tag.
But with JS do, there are the following shortcomings:
1. In case the browser disables JS, it will expire, and write code is to consider compatibility.
2. Maintenance is troublesome, the location of the picture is stored in the array.
So I proposed to use PHP processing, but I and her php are half a bucket of water, I can not think of how to do. Today, a high fortune, see a PHP random display directory of the source code, learn about, and share it.
Take a look at the principle: Get a list of files of a certain type from a directory (usually jpg/gif/png on the web), select an image---Output code by random function.
The PHP code is as follows:
Copy the Code code as follows:
$imglist = ";
Use the $img_folder variable to save the directory where the picture is located, must end with "/"
$img _folder = "images/tutorials/";
Mt_srand (Double) microtime () *1000);
Working with catalog classes
$imgs = Dir ($img _folder);
Check if there is a picture in the directory and generate a list
while ($file = $imgs->read ()) {
if (eregi ("gif", $file) | | eregi ("JPG", $file) | | eregi ("PNG", $file))
$imglist. = "$file";
} closedir ($imgs->handle);
Put all the items in the list in an array
$imglist = Explode ("", $imglist);
$no = sizeof ($imglist)-2;
Generates a random number between 0 and the number of pictures
$random = Mt_rand (0, $no);
$image = $imglist [$random];
Output results
Echo ';
If you want to change the page background through this function, you can change the last sentence to read:
Copy the Code code as follows:
Echo '