简体   繁体   中英

Call different set of random images based on screen resolution: PHP?

I have a homepage that loads random full-screen background images, but has rendering problems on mobile because of (I believe) the size of the images called.

I'm using PHP script to call the images, is it possible to have the PHP call a different set of images if the screen width is below 1080px?

Here is the page: http://agentboris.com/

The PHP before the html in the html file:

<?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
?>

And the CSS styling to make it happen (I think!):

<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>

Thanks for your help.

You can do it with javascript/jQuery:

Having images with name as:
img-XY.gif
X: number relative to resolution, for example 8 will be for around 800px width
Y: number of image (0,1,2,3... up to 9 in the example) for every resolution

<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>

So you will need some like:

/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

With 6 images (0 to 5) and having a group of images for every 300px of width, the code should be like:

   <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM