如何动态更改CSS

How to Change CSS Dynamically

本文关键字:CSS 动态 何动态      更新时间:2023-09-26

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

这是横幅代码

<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生成的css。这甚至很容易。

只需像这样启动php文件:

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

我同意本的观点。如果你在你的页面中嵌入一个小的css部分,你可以在那里放置.contanerTop css代码。然后,把你的代码放在页面上。所以,在你的实际网页中,放上这个:

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

当然,你的后台url在重新加载之前不会更新。如果你决定这样做,不要忘记从你现有的css中提取.contanerTop定义。说了这么多,我真的很喜欢戴斯特洛伊的回答。非常好。我从没想过要那样做。

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

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

这将设置从数据库获取的背景。

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

示例-

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

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