根据屏幕分辨率调用不同的随机图像集:PHP?

时间:2015-03-17 15:54:43

标签: php

我有一个加载随机全屏幕背景图片的主页,但由于(我相信)所调用图像的大小,因此在移动设备上存在渲染问题。

我正在使用PHP脚本来调用图像,如果屏幕宽度低于1080px,是否可以让PHP调用不同的图像集?

以下是页面:http://agentboris.com/

html文件中html之前的PHP:

<?php
  $bg = array('bg-01.gif', 'bg-02.gif', 'bg-03.gif', 'bg-04.gif', 'bg-05.gif', 'bg-06.gif', 'bg-07.gif', 'bg-08.gif', 'bg-09.gif', 'bg-10.gif', 'bg-11.gif', ); // 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样式来实现它(我想!):

<style type="text/css">
<!--
body{
background: url(backgrounds/<?php echo $selectedBg;?>) no-repeat center center fixed;
-webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
-->
</style>

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你可以使用javascript / jQuery:

图片名称为:
IMG-X-Y.gif
X:相对于分辨率的数字,例如8将是大约800px宽度的数字 Y:每个分辨率的图像数(0,1,2,3 ...在示例中为9)

<script>
var w = $( window ).width();
image = "img-" + Math.floor(w/100) + "-" + Math.floor(Math.random() * 10) + ".gif";
$('body').css("background-image", "url('/imagePath/" + image + "')");  
</script>

所以你需要一些像:

/imagePath/
   img-0-0.gif   // images from 0 to 299px width
   img-0-1.gif
   img-0-2.gif
   img-0-3.gif
   img-0-4.gif
   img-0-5.gif
   img-1-0.gif   // images from 300 to 599px width
   img-1-1.gif
   img-1-2.gif
   img-1-3.gif
   img-1-4.gif
   img-1-5.gif
   img-2-0.gif   // images from 600 to 899px width
   img-2-1.gif
   img-2-2.gif
   img-2-3.gif
   img-2-4.gif
   img-2-5.gif
   img-3-0.gif   // images from 900 to 1199px width
   img-3-1.gif
   img-3-2.gif
   img-3-3.gif
   img-3-4.gif
   img-3-5.gif
   img-4-0.gif   // images from 1200px width
   img-4-1.gif
   img-4-2.gif
   img-4-3.gif
   img-4-4.gif
   img-4-5.gif

有6张图像(0到5)并且每300px宽度有一组图像,代码应该是这样的:

   <script>
    var w = $( window ).width();
    if (w < 1500) {  //for width resolutions lower than 1500px
        widthId = Math.floor(w/300);
    } else {         // for resolutions of 1500 or higher
        widthId = 4
    }
    image = "img-" + widthId + "-" + Math.floor(Math.random() * 6) + ".gif";
    $('body').css("background-image", "url('/imagePath/" + image + "')");  
    </script>
相关问题