随机背景图片 CSS3 [英] Random background images CSS3
本文介绍了随机背景图片 CSS3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一个小型网站,但是我的背景有 5-6 张图片,我希望每次刷新页面时都让它随机.这就是我在 style.css 中得到的:
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
}
推荐答案
你不能只用html &用于此目的的 css.您应该在客户端(如 javascript)或服务器端(如 php 脚本)进行操作
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)
这里是 php 示例:
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>
这里是 jquery 示例:
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)] + ')'});
这篇关于随机背景图片 CSS3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文