9

私は小さなウェブサイトをやっていますが、背景に 5 ~ 6 枚の画像があり、ページを更新するたびにランダムにしたいと考えています。これは私が 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   
}
4

6 に答える 6

19

この目的で html と css だけを使用することはできません。クライアント側(javascriptなど)またはサーバー側(phpスクリプトなど)で行う必要があります

これがphpの例です:

<?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 の例を次に示します。

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)] + ')'});
于 2013-03-05T18:56:33.513 に答える
8

私はJSを使用します。次の例を見てください。

<html>
<head>
<script type="text/javascript"> 
var totalCount = 8;
function ChangeIt() 
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
}
</script>
</head>
<body> 
// Page Design 
</body> 
<script type="text/javascript"> 
ChangeIt();
</script> 
</html>

画像にランダムな数で適切な番号を付けて、その画像フォルダーに配置する必要があります。

于 2013-03-05T18:59:51.130 に答える
8

jQuery の場合:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {

    var bgArray = ['bg1.jpg', 'bg2.jpg', 'bg3.jpg'];
    var bg = bgArray[Math.floor(Math.random() * bgArray.length)];

    $('body').css('background', bg);

    // If you have defined a path for the images
    var path = 'images/bg/';

    // then you can put it right before the variable 'bg'
    $('body').css('background', path+bg);

}); 
</script>   
于 2013-03-05T18:59:52.877 に答える
3

非常に短いオプション: (ページで php を使用できる場合)。一重引用符で囲まれたファイル名を背景の URL に置き換えます。

background: url('<?php $a = array('darkred.jpg','red.gif','pink.png'); echo $a[array_rand($a)];?>');
于 2013-12-04T00:46:34.647 に答える
0

最後の答えは非常に短いですが、それらを 1 つのフォルダーに入れるとどうなりますか?

<?php
$pt = 'BGs/';  //folder where you put your BGs       
$bg = array($pt.'bg_ants.png', $pt.'bg_boobs.png', $pt.'bg_circles.png' ); // array of filenames
?>
<Body background="<?php echo $bg[array_rand($bg)]; ?>">

1 つのファイルに保存して、他のページでコードを使用するために含めることができます。例: 「rand.htm」として保存します。<body>タグをこのコードに置き換えるだけです。

<?php include("rand.htm"); ?>
于 2013-12-06T06:09:21.823 に答える
0

これは純粋な CSS では不可能です。ウェブサイトの背景画像をランダムに設定するには、javascript を使用する必要があります。

于 2013-03-05T18:57:23.020 に答える