且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

随机背景图片CSS3

更新时间:2022-10-19 13:47:56

您不能仅使用HTML和放大器; CSS用于这一目的。你应该这样做客户端(如使用JavaScript)或服务器端(如PHP脚本)

下面是PHP的例子:

 < PHP
  $ BG =阵列('BG-01.JPG,BG-02.JPG,BG-03.jpg,BG-04.jpg,BG-05.jpg,BG-06。 JPG,BG-07.jpg'); //文件名的数组  $ I =兰特(0,计数($ BG)-1); //生成的数组随机数大小
  [$ i]于$ BG$ selectedBg =; //设置为一个选择的变量等于随机文件名
?><风格类型=文/ CSS>
<! -
身体{
背景:网址(?图像/< PHP的echo $ selectedBg;>)不重复;
}
- >
< /风格>

下面是jQuery的例子:

  VAR图像= ['image1.jpg,image2.jpg','image3.jpg','image4.jpg','image5.jpg'];
$('HTML')的CSS({'背景图像':'网址(图片/+图像[Math.floor(的Math.random()* images.length)] +')'});

I am doing small website, however I have like 5-6 images for my background, and I want to make it random every time I refresh the page. This is what I got in style.css :

html {   
    background:  url(image/l2.jpg) no-repeat center center fixed
    -webkit-background-size: cover
    -moz-background-size: cover
    -o-background-size: cover
    background-size: cover   
}

You cant use only html & css for this purpose. You should do it client side(like with javascript) or server side(like a php script)

Here's php example:

<?php
  $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.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 type="text/css">
<!--
body{
background: url(images/<?php echo $selectedBg; ?>) no-repeat;
}
-->
</style>

Here's jquery example:

var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
$('html').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});