假设我的站点有一个预加载器屏幕。我想在每次网站加载时随机设置它。我想使用 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/