首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从多个子文件夹中随机设置背景图像

从多个子文件夹中随机设置背景图像
EN

Stack Overflow用户
提问于 2019-08-31 13:25:12
回答 1查看 38关注 0票数 0

我尝试从几个子文件夹中随机设置网页的背景图像,但图像名称相同。例如:邮件格式可以是配置文件,然后是mlhrs,然后是RVS。

在(RVS)文件夹中,您将有x个子文件夹,并且在每个子文件夹中都有profile.jpg映像

我的目标是,每次页面重新加载时,图像都会从所有(RVS)子模板随机更改

我该怎么做呢?

我找到了这段代码,它几乎就是我需要的,但我不知道如何才是最好的方式:

你能帮帮我吗?非常感谢

代码语言:javascript
复制
<!DOCTYPE HTML>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
        <title>404</title>
    </head>

    <body id="Background404">
        <p>404-Page not found. <a href="http://url.com">Home.</a></p>
    <?php
        $dir = './images';
        $fileNames = array();
        if(is_dir($dir)){
            $handle = opendir($dir);
            while(false !== ($file = readdir($handle))){
                if(is_file($dir.'/'.$file) && is_readable($dir.'/'.$file)){
                    $fileNames[] = $file;
                }
            }
            closedir($handle);
            $fileNames = array_reverse($fileNames);
            print_r($fileNames);
        }
        $totalLength = count($fileNames);
        $randInt = rand(0, $totalLength -1);
        $randFile = $fileNames[$randInt];
        echo $randFile;
        echo "<style> #Background404{background: url('./images/$randFile');}</style>";
    ?>

    </body>
</html>
EN

回答 1

Stack Overflow用户

发布于 2019-08-31 14:04:59

随机使用随机洗牌

下面是解决方案代码

代码语言:javascript
复制
        $fileNames = shuffle($fileNames); // Shuffle All Array Files
        $randFile = end($fileNames); /*Get Last File Name Array (Last File Is Always Randomly, Becase We Did shuffle before get last element*/
        echo $randFile;
        echo "<style> #Background404{background: url('./images/$randFile');}</style>";````
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57735416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档