php - 使用 php 在 head 标签内设置一个 css 属性

标签 php html css

假设我的站点有一个预加载器屏幕。我想在每次网站加载时随机设置它。我想使用 php 使我的 css 文件的 background 属性随机化。这是 css 文件的演示代码:

<style>
   .se-pre-con {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;

   <?php
    $number=rand(1,4);
    $url=base_url('media');
    if($number==1)
    {
        echo "background:"."url(". $url."/images/loader-64x/infinity1.gif) center no-repeat #fff;";
    }
    if($number==2)
    {
        echo "background:"."url(". $url."/images/loader-64x/infinity2.gif) center no-repeat #fff;";

    }
    if($number==3)
    {
        echo "background:"."url(". $url."/images/loader-64x/infinity3.gif) center no-repeat #fff;";
    }
    if($number==4)
    {
          echo "background:"."url(". $url."/images/loader-64x/infinity4.gif) center no-repeat #fff;";
    }   
?>
}
</style>

我只是想让background 属性每次都不同。但我认为它不起作用,因为我根本没有看到任何预加载器屏幕。 php里面设置背景有没有错误?

最佳答案

问题出在 xampp 中的 base_url 函数。请改用下面的代码,如果您将图像放在正确的位置,它对我来说工作正常

<style>
    .se-pre-con{
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    <?php
    $number=rand(1,2);
    $url='media';
    if($number==1)
    echo "background:url('".$url."/images/loader-64x/infinity1.gif') center no-repeat #fff;";
    else if($number==2)
        echo "background:url('".$url."/images/loader-64x/infinity2.gif') center no-repeat #fff;";
    ?>
    }
</style>

我怎么有更好的解决方案,用 html 而不是 css 玩 php

<html>
<head>
<style>
   .se-pre-con{
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    }
    .bg1{
        background:url('media/1.jpg') center no-repeat #fff;
    }
    .bg2{
        background:url('media/2.jpg') center no-repeat #fff;
    }
</style>
</head>
<body>
<div class="se-pre-con <?php $arr=array('bg1','bg2'); echo $arr[array_rand($arr)];?>"></div>
Hello World
</body>
</html>

其中 bg1 和 bg2 是为不同背景创建的类,并为预加载器 div 选择一个随机的 bg 类

关于php - 使用 php 在 head 标签内设置一个 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582371/

相关文章:

html - 输入元素在引导网格中具有意外的包装行为

html - 这可能与 Dreamweaver 中的正则表达式有关吗?

java - HTML5 模式下的 AngularJS + Java

JavaScript CSS 框架

php - 使用 pdo 检查 2 个条件

php - 失败(104 : Connection reset by peer)

php - 检查 file_get_contents 何时完成

未加载 PHP 配置文件? (Mac OS X 优胜美地)

javascript - HTML/CSS 顶部水平导航栏

css - 如何使中间框中的内容垂直居中?