用新图片刷新页面

5

我网站上的图片目前没有动静:

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

每次页面刷新时,我希望图片都是不同的,比如自动更换为2.jpg、3.jpg、10.jpg等等(有数百个可供选择的)。能否有人帮我想一个解决方案?我不太擅长这个,而且这是我的第一个站点。谢谢。

动态更改CSS背景图片 - Ajoy
是的,但它说的是这个:'url(img / rainbow.jpg)', 'url(img / chickens_on_grass.jpg)' 'url(img / cattle_on_pasture.jpg)' 'url(img / csa_bundle.jpg)' - 我有成百上千个。 - Brian Fitzpatrick
4个回答

2
我认为单独使用CSS无法做到这一点,以下是一个答案:

随机

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)] + ')';
}

这将在每次访问页面时加载随机图片。

指定顺序

为了按顺序加载它们:第一次是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']] + ')';

};

我很确定backgroundImage的图片URL必须位于'url()'语句中,否则它将无法工作。就像这样...document.body.style.backgroundImage = 'url(pix.jpg);' - user4698813
1
@AlfonsoGarnett 是的,我忘了。已修复。 - Downgoat
<?=scandir('/images')?> 会导致 "Notice: Array to string conversion"。 - HandyDan
不是很有效,你能告诉我哪里错了吗? http://codepad.org/gUVeDFbS#output - Brian Fitzpatrick
你的第三个答案,就是Brian所提到的那个。你唯一有循环的解决方案。 - HandyDan
显示剩余8条评论

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

希望它有所帮助。 谢谢。

0

我看到了很多JS的解决方案,但最有可能你需要一个php的解决方案,因为我相信你不想在文件中放置数百个图像的名称。所以如果你有一些php编程知识,那么可以尝试以下方法:

  1. 生成一个随机数。假设它是42。

  2. 逐个读取文件名(http://php.net/manual/en/function.readdir.php

  3. 一旦到达第42个文件,将其传递给页面。

你可以直接将文件名放入css中,也可以将php页面作为背景图片源返回图像。无论哪种情况,以上步骤都能帮助你实现你想要的效果。


如果文件名和类型不同,上述方法可行。然而,如果文件名是数字且所有文件都具有相同的扩展名,则仅生成一个数字并将其用作文件名比上述方法略快。

然而,它仍然比大多数JS解决方案更快。请记住,JS在客户端运行。这意味着它将在页面加载后执行。使用JS时,文件需要尽可能小。否则,在请求返回之前,页面将加载但您将没有背景。考虑到所有这些延迟,我不会认为JS比PHP高效。

虽然你总可以让它变得漂亮并渐变出现:)

很抱歉,但你的解决方案不够好。为什么不在执行时随机选择一张图片,而要向服务器发起请求呢? - RisingSun
var a = new XMLHttpRequest(); a.open('GET', prefix+i+extension, false); a.send(); 变量a等于新的XMLHttpRequest(); a.open('GET',prefix+i+extension,false); a.send(); - RisingSun
如果你正在使用 PHP,你不会希望一个一个地读取文件名,那样相当低效。在进行服务器端代码时,你需要尽可能高效。 - Downgoat
1
不算真正意义上的,因为代码和文件都在同一台机器上。 - RisingSun
无论如何,好主意 :) 只是有点低效 在我看来 - Downgoat

-1

不需要使用AJAX

为什么应该使用PHP

使用PHP的附加好处是,我们可以使所有您要做的就是将图像放入文件夹中,它将自动添加到随机列表中!这对于可维护性非常有用。您只需编写一次代码,然后让它保持不变!

在我看来,使用AJAX没有任何附加好处。每次添加图像时,您都必须将其添加到JS图像数组中。但是,我不知道您的确切情况。

重要提示

到目前为止,提到PHP的所有其他解决方案都未提到一个非常重要的部分...您正在工作的页面必须被解析为PHP文件。 有两种方法可以实现:

  1. 通过.htaccess将html / htm页面解析为php页面(高级
  2. 将页面扩展名更改为“.php”(简单

(我的解决方案要求您的页面被解析为PHP)


解决方案 1

我会使用 JavaScript 从 PHP 生成的列表中随机选择图像,然后附加 CSS 将背景图像应用于 window.onload 事件之前的页面。

PHP 和 JavaScript 随机

将以下内容附加到页面头部:

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

将以下内容添加到页面头部:

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

更改背景图像的PHP?现在你的解决方案对于这样一个简单的任务来说有点太疯狂了。 - Downgoat
不是这样的,它对所有用户都更加易于访问。用户无需使用JavaScript即可查看图像。 - HandyDan
另外,我使用AJAX的唯一原因是为了避免每次更新数组。它将获取目录中的所有图像。 - Downgoat
@vihan1086 抱歉,但我认为向服务器发出未知数量的图像的 AJAX 请求并不是一个好的解决方案。 - HandyDan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接