【问题标题】:Refreshing page with a new image [duplicate]使用新图像刷新页面[重复]
【发布时间】:2015-07-08 02:34:06
【问题描述】:

我的网站上目前有一个停滞的图像:

    <!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 等。 (有数百种可供选择)

有人可以帮我解决吗?我不太擅长这个,这是我的第一个网站。

谢谢。

【问题讨论】:

  • 是的,但是上面写着:'url(img/rainbow.jpg)', 'url(img/chickens_on_grass.jpg)' 'url(img/cattle_on_pasture.jpg)' 'url(img /csa_bundle.jpg)' - 我确实有数百个。

标签: javascript php html css web


【解决方案1】:

我不认为仅靠 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);'
  • @AlfonsoGarnett 是的,我忘记了。固定
  • &lt;?=scandir('/images')?&gt; 会导致“注意:数组到字符串的转换”
  • 不为我工作。你能告诉我我做错了什么吗? codepad.org/gUVeDFbS#output
  • 到目前为止,您的 ajax 不会随机化图像,它会始终显示 1.jpg。循环从 1 开始,永远不会再进一步​​。 AJAX 总是会陷入无限循环。要至少修复无限循环,请将您的 indexImages 声明移到 window.onload 之外
【解决方案2】:

您可以使用 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

希望对您有所帮助。 问候,

【讨论】:

    【解决方案3】:

    我看到了所有这些 JS 解决方案,但很可能您需要一个 php 解决方案,因为我确信您不想将数百个图像的名称放在一个文件中。所以如果你有一些 php 编程知识,那就试试这个吧。

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

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

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

    您可以将文件名直接放在 css 中,也可以将 php 页面作为返回图像的背景图像源。无论哪种情况,上述步骤都会为您提供您想要的。


    如果文件名和类型不同,上述方法效果很好。但是,如果文件名是数字并且所有文件都是相同的扩展名,那么只生成一个数字并将其用作文件名比上述方法稍快。

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

    虽然你总是可以让它变得漂亮并淡入或其他东西:)

    【讨论】:

    • 很抱歉,您的解决方案很糟糕。为什么不直接在执行时抓取随机图像而不是向服务器发出请求?
    • var a = new XMLHttpRequest(); a.open('GET', prefix+i+extension, false); a.send();
    • 如果你使用 PHP,你不会想一个一个地读取文件名,那是非常低效的,在做服务器端代码时,你希望尽可能高效
    • 不是真的,因为代码和文件在同一台机器上
    • 无论如何,好主意 :) 只是效率有点低在我看来
    【解决方案4】:

    不需要 AJAX

    为什么你应该使用 PHP

    使用 PHP 的额外好处是我们可以做到这一点,您只需将图像拖放到文件夹中,它就会自动添加到随机列表中!这对于可维护性非常有用。您只需编写一次代码,就不用管它了!

    在我看来,使用 AJAX 并没有额外的好处。每次添加图像时,都必须将其添加到 JS 图像数组中。但是,我不知道您的具体情况。

    重要

    到目前为止,所有其他提到 PHP 的解决方案都没有提到一个非常重要的部分……您正在处理的页面必须被解析为 PHP 文件。 有两种方法可以做到这一点:

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

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


    解决方案 1

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

    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 用于更改背景图像?现在你的解决方案对于这样一个简单的任务来说有点太疯狂了
    • 并非如此,所有用户都可以访问它。用户不需要 JavaScript 即可查看图像。
    • 另外,我使用 AJAX 的唯一原因是不必每次都更新数组。它将获取目录中的所有图像
    • @vihan1086 抱歉,我不认为向服务器发出 AJAX 请求以获取未知数量的图像是一种好的实践解决方案。
    猜你喜欢
    • 2014-02-14
    • 2012-05-23
    • 2019-10-14
    • 2011-07-14
    • 2018-03-31
    • 2016-09-04
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    相关资源
    最近更新 更多