dongmaobeng7145 2015-12-24 00:18
浏览 99
已采纳

PHP / CSS随机背景

Trying to get a random background between two images.

The PHP (Before Doctype in index.php):

<?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;
}

The issue is that the background isn't set to either of the images!

EDIT:

Ive moved on to a completley PHP method although it errors:

Line : 5,   Error type : 4
Message : syntax error, unexpected '(', expecting variable (T_VARIABLE) or '$'

Code:

<?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 + ')'            } );
?>
  • 写回答

2条回答 默认 最新

  • dtrvzd1171 2015-12-28 18:49
    关注

    Your css file should have something like this in it

    .one {
    background: url(../img/back1.jpg);
    }
    
    .two {
    background: url(../img/back2.jpg);
    }
    
    .three {
    background: url(../img/back3.jpg);
    }
    

    And your HTML should have

    <body class="<? echo $img ?>">
    

    And then your PHP need only define $img as either one two or three

    <?
    $list = array('one', 'two', 'three' );
    $i = array_rand($list);
    $img = $list[$i];
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真