【问题标题】:How to diplay a random picture as background in html?如何在html中显示随机图片作为背景?
【发布时间】:2023-01-30 19:23:33
【问题描述】:

我制作了一个 html 页面来尝试显示随机图片,因为这里的图片是 index.html

<?php
session_start();
$png = array('png1.jpg', 'png2.jpeg', 'png3.jpg', 'png4.jpg');

$random = rand(0,3);
$picture = "$png[$random]";

?>


<!DOCTYPE HTML>
<html>  

<head>
<style>
body {
background: url(images/<?php echo $picture; ?>) no-repeat;
background-size: cover;
}
</style>
</head>
  
<body>
  
<form action="login.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="text" name="password"><br>
<input type="submit">
</form>

</body>
</html>

我期待它从 $png 数组中放一张随机图片,但唯一的输出是“表单”部分。加上图片没有问题。

【问题讨论】:

  • 如果在 CSS 中硬编码图片 URL 是否有效?顺便说一句,你昨天没有发布这个问题吗?
  • “在 index.html 中”- 文件扩展名是.html吗?您的 Web 服务器是否设置为执行以 html 作为文件扩展名的 PHP 文件?您是否检查过生成的代码(右键单击页面并“查看源代码”)?它看起来是否正确,或者您看到那里的 PHP 代码了吗?
  • 你是什​​么意思唯一的输出是表单部分?这似乎不太可能。您是否使用浏览器开发工具检查输出代码?

标签: php html css


【解决方案1】:

将您的文件从“index.html”保存到“index.php”,这将按您的预期运行您的代码。

PHP文件具有读取和显示HTML代码的能力,但HTML不会自动解析php代码。

如果您只想在 html 文件中使用 PHP 变量,则意味着您需要借助 .htaccess 文件启用一些配置。

【讨论】:

    【解决方案2】:

    如果您使用 rand() php 函数并支持 php 文件,并且 $picture = $png[$random] 在不使用字符串的情况下使用,则此代码中的一些错误首先将文件扩展名 .html 转换为 .php

    <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    
    $png = array('https://www.w3schools.com/images/img_upgrade_300.png', 'https://www.w3schools.com/images/img_mylearning_300.png', 'https://www.w3schools.com/images/img_fullaccess_300.png','https://www.elegantthemes.com/images/home/category-thumb-store.jpg');
    
    $random = rand(0,3);
    $picture = $png[$random];
    
    ?>
    
    <style>
    body {
    background: url('<?php echo $png[$random]; ?>') no-repeat;
    background-size: cover;
    }
    </style>
    
     
    </body>
    </html>
    

    【讨论】:

      【解决方案3】:

      问题已解决,代码没有问题。只是我运行 replit.com 的问题。可以使用 vijay pancholi 的代码在 replit.com 上运行

      【讨论】:

      • 您是否在 replit 项目中托管图像?
      • 我确实在我的 replit 程序中上传了图片。
      • 请不要使用“发布您的答案”按钮提交不试图回答本页顶部问题的内容。如果您想对另一个答案发表评论,请使用其正下方的“添加评论”链接。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2018-05-07
      • 2017-09-02
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多