尝试在两张图片之间获得随机背景。
PHP(在index.php中的Doctype之前):
<?php
$bg = array('back1.jpg', 'back2.jpg' ); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>
CSS:
body {
height: 100%;
margin: 0;
color: #474747;
font: 13px/23px 'Exo 2', sans-serif;
min-width: 1186px;
background: url( ../img/<?php echo $selectedBg; ?>) no-repeat 50% 50%;
background-size: cover;
background-attachment: fixed;
}
问题是背景未设置为任何一个图像!
编辑:
我已经转向了一个完整的PHP方法,尽管它有错误:
Line : 5, Error type : 4
Message : syntax error, unexpected '(', expecting variable (T_VARIABLE) or '$'
代码:
<?php
$bg = array('back1.jpg', 'back2.jpg' ); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
$('body').css( { 'background-image': 'url( img / ' + echo $selectedBg + ')' } );
?>
答案 0 :(得分:1)
您正在寻找的是
array_rand();
PHP手册:http://php.net/manual/en/function.array-rand.php
为您的PHP:
<?php
$bg = array('back1.jpg', 'back2.jpg' ); // array of filenames
$i = array_rand($bg); // generate random number size of the array
$selectedBg = $bg[$i]; // set variable equal to which random filename was chosen
?>
答案 1 :(得分:1)
你的css文件应该包含这样的内容
.one {
background: url(../img/back1.jpg);
}
.two {
background: url(../img/back2.jpg);
}
.three {
background: url(../img/back3.jpg);
}
你的HTML应该有
<body class="<? echo $img ?>">
然后您的PHP只需将$img
定义为one
two
或three
<?
$list = array('one', 'two', 'three' );
$i = array_rand($list);
$img = $list[$i];
?>