如何动态更改CSS

时间:2012-07-13 14:04:12

标签: php javascript jquery html

我需要管理员才能更改/更新我网站的横幅。

这是横幅代码

<div class="containertop">This depends on the background of the div</div>

这是

的CSS
.containertop
{
     width:1000px;
     height:300px;  
     **background:url(../images/1.png) no-repeat center;**
     margin: 0 auto;
     margin-top: 40px;
}

我想要发生的事情与Facebook封面照片相同。 上传新横幅时,将更新CSS(类似的内容)。 但是,当然,必须从数据库中提取新的横幅。

所以我认为CSS会变成这样:

获取已保存的横幅源,然后:

background:url(<?php echo $row['image']; ?>);

但是我可以在CSS txt中与数据库(包括'dbname.php')建立PHP连接吗?

4 个答案:

答案 0 :(得分:3)

没有什么能阻止你提供PHP生成的CSS。这甚至很容易。

只需启动您的php文件:

<?php
header("Content-Type: text/css");

答案 1 :(得分:1)

您可以在加载php文件时设置containertop背景。

<?php
echo "<style>.containertop{ background:url(../images/".$row['image'].") no-repeat center;}</style>"
?>

这将设置从db。

获取的背景

答案 2 :(得分:1)

我同意本。如果你在页面中创建一个小的嵌入式css部分,你可以将.containerTop css代码放在那里。然后,将您的代码放在页面中。 因此,在您的实际网页中,请输入:

<style type="text/css">
.containertop{
width:1000px;
height:300px;  
background:url(<?php echo $row['image']; ?>);
margin: 0 auto;
margin-top: 40px;
}
</style>

当然,您的后台网址在重新加载之前不会更新。如果您决定这样做,请不要忘记从现有的CSS中取出.containerTop定义。 说了这么多,我真的很喜欢dystroy的答案。非常好。我从来没有想过这样做。

答案 3 :(得分:0)

好吧,您可以使用jQuery来更改/覆盖CSS文件。

示例 -

$('.containertop').css('backgroud','url(images/change.jpg) repeat');

$('.containertop').css('backgroud','url(<?php echo $images_url ?>) repeat');