随机背景与背景叠加?

时间:2017-01-08 02:21:58

标签: javascript jquery html css

您好我正试图通过叠加方式随机化我的网站背景,但我在获取随机背景时遇到问题。

这就是我正在使用的

.css / .php

#intro {
		background:
          /* top, transparent black gradient */ 
      linear-gradient(
      rgba(0, 0, 0, 0.7), 
      rgba(0, 0, 0, 0.7)

 ),
 /* bottom, image */
        
        url(/images/<?php echo $selectedBg; ?>);
		background-size: 100% auto, cover;
		background-attachment: fixed, fixed;
		background-position: top left, bottom center;
		background-repeat: repeat, no-repeat;
        width: 100%;
        height: auto;


	}
<?php
  $bg = array('bg-01.png', 'bg-02.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
?>

我已经检查了bg-01.png,bg-02.jpg的文件名并且是正确的。如果我做错了,将非常感谢帮助。

2 个答案:

答案 0 :(得分:0)

将Css和php代码保存在一个文件中,然后在css

之后首先加载php代码
<?php
      $bg = array('bg-01.png', 'bg-02.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
?>

<style> 
     #intro {
        background:
          /* top, transparent black gradient */ 
      linear-gradient(
      rgba(0, 0, 0, 0.7), 
      rgba(0, 0, 0, 0.7)

 ),
 /* bottom, image */

        url(/images/<?php echo $selectedBg; ?>);
        background-size: 100% auto, cover;
        background-attachment: fixed, fixed;
        background-position: top left, bottom center;
        background-repeat: repeat, no-repeat;
        width: 100%;
        height: auto;


    }

 </style>

答案 1 :(得分:0)

为什么你还想使用php呢?组合css和php时非常讨厌的编码方式。

javascript方式更加干净。

<script type="text/javascript">
$(document).ready(function() {
    var bgList = ['bg-01.png', 'bg-02.png'];
    var bg = bgList[Math.floor(Math.random() * bgList.length)];

    $('#intro').css('background', bg);

    var path = '/images/';
    $('#intro').css('background', path+bg);
}); 
</script>