Page refresh with a new image

Currently, my site has a stagnant image:

    <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="/stylesheets/normalize.css" media="all" rel="stylesheet" />
  <link href="/stylesheets/master.css" media="all" rel="stylesheet" />

<script>
window.onload = function () {

    var images = [],
        i=1, indexImages = true,
        prefix = '../image/',
        extension = '.jpg';

    while (indexImages) {
        var a = new XMLHttpRequest(); a.open('GET', prefix+i+extension, false); a.send();

        if (a.status != 404) { i += 1; images.push(prefix+i+extension); } else {
            indexImages = false;

            localStorage['backgroundIndex'] = !localStorage['backgroundIndex']?0:+localStorage['backgroundIndex']+2>images.length?0:+localStorage['backgroundIndex']+1;
            document.body.style.backgroundImage =  'url(' + images[+localStorage['backgroundIndex']] + ')';

        }
    }

}
</script>

<style>
body {
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
    background-color: black;

    border-bottom: 8px solid  #7D8A28;
}

</style>

</head>
<body>
  <section id="card">
  </section>
</body>
</html>

It's just that I want it to be a different image every time the page is refreshed, so it automatically changes to 2.jpg, 3.jpg, 10.jpg, whatever. (There are hundreds to choose from)

Can someone help me with a solution? I am not very good at this, and this is my first site.

Thank.

+4
source share
4 answers

I don't think that only CSS can do this, here is the answer:

Random

window.onload = function () {
    var images = [
        'image/1.png',
        'image/2.png',
        'image/3.png',
        'image/4.png'
    ];

    document.body.style.backgroundImage = 'url(' + images[Math.floor(Math.random()*images.length)] + ')';
}

This will load a random image every time you visit the page.


Specified Order

: image1, image2. , . :

window.onload = function () {
    var images = [
        'image/A.png',
        'image/B.png',
        'image/C.png',
        'image/D.png'
    ];

    localStorage['backgroundIndex'] = !localStorage['backgroundIndex']?0:+localStorage['backgroundIndex']+2>images.length?0:+localStorage['backgroundIndex']+1;

    document.body.style.backgroundImage =  'url(' + images[+localStorage['backgroundIndex']] + ')';
}

(, )

,

window.onload = function () {

    var images = [],
        i = 1,
        prefix = 'image/',
        extension = '.png',
        max = 1000;

    function index() {
        var a = new XMLHttpRequest();
        a.open('GET', prefix + i + extension, false);
        a.send();
        a.onreadystatechange = function () {
            if (a.readyState === 4) {
                if (a.status != 404) {
                    i += 1;
                    images.push(prefix + i + extension);
                    i < max ? index();
                } else {}

                localStorage['backgroundIndex'] = !localStorage['backgroundIndex'] ? 0 : +localStorage['backgroundIndex'] + 2 > images.length ? 0 : +localStorage['backgroundIndex'] + 1;
                document.body.style.backgroundImage = 'url(' + images[+localStorage['backgroundIndex']] + ')';

            }

        };
    }

    index();
}

</" >

PHP, , , . PHP, . :

window.onload = function () {
    var images = (JSON.parse("<?=scandir('../images')?>")||[]).filter(function (a) {  return ['.', '..'].indexOf(a) < 0;  });

    document.body.style.backgroundImage =  'url(' + images[+localStorage['backgroundIndex']] + ')';

};
+1

JavaScript. , , , . , . :

var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg"];

var randomNumber = Math.floor((Math.random() * images.length));
//images[randomNumber] contains your random image
Hide result

, . ,

+1

JS-, , , php, , . , php, .

css php- , . , .


, . , , , , , .

, JS. , JS . , . JS . , , . , JS PHP.

- :)

0

AJAX

PHP

PHP , , , , ! . !

, AJAX. , , JS. .

!

, PHP, ... , , PHP. :

  • html/htm php .htaccess()
  • ".php" ()

( , PHP)


1

JavaScript PHP , CSS, window.onload.

PHP JavaScript Random

:

<script type="text/javascript">
    <?php
    // Path to image can be a relative or absolute path. I recommend absolute.
    // The following is my absolute path.
    $img_dir_path = '/rand-img/images/';

    // Get directory list. If using absolute, prepend $_SERVER['DOCUMENT_ROOT'] for php
    $dir_listing  = scandir($_SERVER['DOCUMENT_ROOT'].$img_dir_path, 1);

    // array_diff() to remove '.' & '..' from front of $dir_listing array
    $img_array    = array_diff( $dir_listing, array('.', '..') );
    ?>

    // JavaScript variables
    var img_dir_path = '<?php echo $img_dir_path ?>';
    var img_array    = <?php echo json_encode($img_array) ?>;
    var rand_index   = Math.floor(Math.random() * img_array.length);
    var img_path     = img_dir_path + img_array[rand_index];

    // no need to wait for window.onload if we append actual style tag
    var css   = 'body { background-image: url('+img_path+') !important; }',
        head  = document.head || document.getElementsByTagName('head')[0],
        style = document.createElement('style');

    style.type = 'text/css';

    if (style.styleSheet){
        style.styleSheet.cssText = css;
    } else {
        style.appendChild(document.createTextNode(css));
    }

    head.appendChild(style);
</script>

PHP . JavaScript , .


2

, . , , .

PHP Random

:

<?php
// Path to image can be a relative or absolute path. I recommend absolute.
// The following is my absolute path.
$img_dir_path = '/rand-img/images/';

// Get directory list. If using absolute, prepend $_SERVER['DOCUMENT_ROOT'] for php
$dir_listing  = scandir($_SERVER['DOCUMENT_ROOT'].$img_dir_path, 1);

// array_diff() to remove '.' & '..' from front of $dir_listing array
$img_array    = array_diff( $dir_listing, array('.', '..') );

// Random number based off size of $img_array
$random_index = mt_rand(0, count($img_array)-1);

// Build image path
$image_path   = $img_dir_path . $dir_listing[ $random_index ];

?>

<style type="text/css">
    body {
        background-image: url("<?php echo $image_path ?>");
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-position: center;
        background-color: black;

        border-bottom: 8px solid  #7D8A28;
    }
</style>
-1
source

All Articles