我正在尝试制作随机背景。
background:url(images/background/background-image.php) no-repeat fixed;
background-size: 100%;
它适用于firefox、safari和IE,但不适用于chrome。
background-image.php
<?php
$folder = '.';
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
$img = null;
if (substr($folder,-1) != '/') {
$folder = $folder.'/';
}
if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if ( isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) && file_exists( $folder.$imageInfo['basename'] ) ) {
$img = $folder.$imageInfo['basename'];
}
} else {
$fileList = array();
$handle = opendir($folder);
while ( false !== ( $file = readdir($handle) ) ) {
$file_info = pathinfo($file);
if (isset( $extList[ strtolower( $file_info['extension'] ) ] ) ) {
$fileList[] = $file;
}
}
closedir($handle);
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder.$fileList[$imageNumber];
}
}
if ($img!=null) {
$imageInfo = pathinfo($img);
$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
header ($contentType);
readfile($img);
} else {
if ( function_exists('imagecreate') ) {
header ("Content-type: image/png");
$im = @imagecreate (100, 100) or die ("Cannot initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color);
imagepng ($im);
imagedestroy($im);
}
}
?>
而不是制作一个生成实际图像文件的脚本。我会将脚本引用作为文件的链接。例如,如果在目录images
中有10个随机图像,我会将PHP的rand
函数与scandir
一起使用。
注意:我还没有测试下面的代码。这只是一个"粗略的想法"。
<?php
$website_path = "http://www.example.com/".$GET['imgpath'];
$list = scandir($_GET['imgpath']);
if(count($list)>0){ //yes images in directory
$random = rand(0,count($list));
$random_path = $list[$random];
}else //no images in directory
$random_path = "/images/error.php";
$random_path = $website_path."/".$random_path;
echo "background:url('$random_path');";
?>
background-size:100%;
还要注意,您没有在background:url('...');
CSS样式周围包含单个引号。如果我读对了你的代码,你会发现你可能已经处理过了复杂的事情。
你能把CSS放在一个PHP文件中,并使用一个变量列出背景图像的路径吗?
background:url(<?=$bgimage?>) no-repeat fixed;
让您的PHP脚本输出变量$bgimage
注意缩写
<?=$bgimage?>
和说是一样的
<?php echo $bgimage; ?>