每个用户的动态css


dynamic css per user

我的网站上有一个gamimng部分,允许用户使用颜色(蓝色、红色和绿色)快速显示统计数据的状态。

我想根据每个用户生成这样的东西。到目前为止我有这个:

<style>
.box2 {
    height: 20px;
    background: blue;
    float:left;
    width:120px;
}
.box3 {
    height: 20px;
    background: green;
    float:left;
    width:30px;
}
.box1 {
    height: 20px;
    background: red;
    float:left;
    width:140px;
}
</style>
<div>
    <div class="box1"></div>
    <div class="box2"></div>
    <div class="box3"></div>
</div>

我应该把css直接放在页面上吗?使用php实现这一点的最佳方式是什么?

您可以始终使用PHP生成的文件,并将其作为CSS文件包含,如:

<link rel="stylesheet" type="text/css" href="/css/userstats.php" />

然后在这个文件中,您可以使用当前会话来查找用户统计信息,然后使用PHP生成。别忘了放标题:

header("Content-type: text/css");

示例php:

background: #<?php echo $colorX; ?>; // assuming the $colorX is HEX

如果你更喜欢使用.htaccess来重写文件,这样它看起来就不那么明显了,比如:

RewriteEngine On
RewriteBase /
RewriteRule ^css/userstats.css$ /path/to/generatedfile.php [L,NC]

所以你可以使用:

<link rel="stylesheet" type="text/css" href="css/userstats.css" />

示例代码:

<style>
div.bar {
    height: 25px;
}
div.bar div {
    display: block;
    float:left;
    height: 25px;
    margin: 0;
    padding: 0;
    position: relative;
}
div.bar div.red {
    background: #DD3030;
    -webkit-box-shadow: -5px 0px 8px 2px #DD3030;
    -moz-box-shadow: -5px 0px 8px 2px #DD3030;
    box-shadow: -5px 0px 8px 2px #DD3030;
    width:140px;
    -moz-border-radius-topleft: 8px;
    -moz-border-radius-topright: 0px;
    -moz-border-radius-bottomright: 0px;
    -moz-border-radius-bottomleft: 8px;
    -webkit-border-radius: 8px 0px 0px 8px;
    border-radius: 8px 0px 0px 8px;
    z-index:10;
}
div.bar div.blue {
    background: #3388DD;
    -webkit-box-shadow: 0px 0px 8px 2px #3388DD;
    -moz-box-shadow: 0px 0px 8px 2px #3388DD;
    box-shadow: 0px 0px 8px 2px #3388DD;
    width:120px;
    z-index:5;
}
div.bar div.green {
    background: #1CAD32;
    -webkit-box-shadow: 5px 0px 8px 2px #1CAD32;
    -moz-box-shadow: 5px 0px 8px 2px #1CAD32;
    box-shadow: 5px 0px 8px 2px #1CAD32;
    width:30px;
    -moz-border-radius-topleft: 0px;
    -moz-border-radius-topright: 8px;
    -moz-border-radius-bottomright: 8px;
    -moz-border-radius-bottomleft: 0px;
    -webkit-border-radius: 0px 8px 8px 0px;
    border-radius: 0px 8px 8px 0px;
    z-index:10;
}
</style>
<div class="bar">
    <div class="red"></div>
    <div class="blue"></div>
    <div class="green"></div>
</div>

jsfiddle:http://jsfiddle.net/g9Vrx/

如果颜色是完全可自定义的,那么最好的方法是在每个用户每次加载页面时生成CSS,或者在用户更改其首选项中的颜色时生成一次,并将其存储在缓存或数据库中。然后提取并使用它。

同样,如果颜色是完全可自定义的(不像两个预定义的颜色),那么你应该在HTML页面中包含CSS,因为用PHP修改外部CSS文件是相当复杂和不必要的。