我已经创建了一个皮肤开关,它的工作很好,但代码是混乱的。
我保存了一个cookie,然后对于一些定义的css类,我将'-userDelectedColourFromTheCookie‘添加到css类的末尾,以便在页面上应用它。
到目前为止,我在html代码中这些类的每个实例的末尾都添加了一个短的php行,正如我已经说过的,它正在工作。
我倾向于只在整个页面上运行一次php代码,并更新包含所需类的数组的所有出现情况,如上面所示。
我把这个放在我的页面顶端:
<?php
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], array("Blue","Red","Grey","Ochre","Mauve"))) echo $classList."-".strtolower($_COOKIE["Theme"]);
?>
<!DOCTYPE html>
... etc我正在定义一个css类数组,然后从cookie中读取用户颜色并将其附加到css类中。
例如,默认的类可能是‘主题-3’,但是用户选择蓝色皮肤,然后这个类变成‘主题-3-蓝色’等等。
但这不管用。
任何帮助都将不胜感激。
发布于 2021-06-11 21:29:37
不要弄乱元素类列表。使用CSS文件应用您想要的颜色。
从一个基本的CSS设计文件开始:
p {
margin-left:10px
font-size: 12pt;
}
h1 {
font-size: 24pt;
}
div {
margin: 10px;
padding 20px;
}然后创建具有不同颜色选择的CSS颜色文件:
blue.css
p {
color:blue;
}
h1 {
color: darkblue;
background-color: lightblue;
}red.css
p {
color:red;
}
h1 {
color: maroon;
background-color: pink;
}default.css
p {
color:black;
}
h1 {
color:white;
background-color:black;
}然后加载所需的颜色主题。
<?php
if (isset($_COOKIE['theme'] && in_array($_COOKIE['theme'], ['red','blue'])) {
$themeCSS = '<link rel="stylesheet" href="'.$_COOKIE['theme'].'.css">';
} else {
$themeCSS = '<link rel="stylesheet" href="default.css">';
}然后在您的<head>中回显<head>,就像任何其他<head>元素一样
**我在这里使用了标准的HTML元素来说明,但是任何CSS选择器都应该能工作。
发布于 2021-06-11 21:22:54
几种很好的方法。对于类数组来说,这稍微复杂一些,但是如果需要的话,您应该能够调整它(不确定为什么语法突出显示不稳定)。
最后使用输出缓冲和替换:
<?php
ob_start();
?><html>
<head></head>
<body>
<div class="theme-1"></div>
</body>
</html><?php
$themes = array("Blue","Red","Grey","Ochre","Mauve");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], $themes)) {
echo preg_replace('/class="(theme-[^"]+)"/', 'class="$1-' . $_COOKIE['Theme'] . '"', ob_get_clean());
}对于类数组,只需通过输出缓冲以相同的方式进行替换,如下所示:
$replace = array_map(function($v) { return "{$v}-{$_COOKIE['Theme']}"; }, $classList);
echo str_replace($classList, $replace, ob_get_clean());发布于 2021-06-11 21:35:38
我相信您希望通过从cookie中追加选定的颜色主题来更改$classList变量中的类名。
您可以使用array_map函数修改$classList数组的所有元素。
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
$themeColor = $_COOKIE["Theme"]; // blue
$classList = array_map(function($val) use ($themeColor) { return $val.'-'.$themeColor; }, $classList);使用array_map函数后,$classList数组的所有元素都将添加"-blue“。
您可以在这里执行并看到输出,http://sandbox.onlinephpfunctions.com/code/6051282e00be1eb7bb7e6a086de20bbcfe9bcc9f
https://stackoverflow.com/questions/67943395
复制相似问题