想法是网站上有一个设置页面可以普遍更改主题。因此设置页面将包含此链接;
<a href="">Click here to enable dark mode</a>
单击此按钮会向每个页面添加另一个样式表。
<?php echo "<link rel='stylesheet' type='text/css' href='darkmode.css'>"; >
无论如何,这就是想法,网站已构建并添加了 darkmode.css
与 <link rel="stylesheet" href="https://example.com/darkmode.css">
然后在页面上显示暗模式。
我对其他想法持开放态度,例如设置一个简单的 cookie,并且只有在 true 时才激活样式表。我不希望在每个页面上都进行切换,因为这意味着手动编辑所有页面,而且只对某些用户可用。
我假设必须在设置页面上将一个变量设置为 true,但它需要在整个网站上进行,所以
<?php
if ($darkmode = $true)
echo "<link rel="stylesheet" href="https://example.com/darkmode.css">";
?>
我假设需要将类似的东西添加到每个页面,如果是真的,就回显样式?
如有任何帮助,我们将不胜感激,在此先致谢。
UPDATE 1
这些代码都不起作用,但这只是一个例子。管理员会选择一个复选框,如果该框被勾选,页面将读取文件的是/否,然后回显指向附加样式表的链接。
<form action="preference.php" method="post">
<input type="checkbox" id="preference" name="preference">
</form>
<?php
$preference = $_POST["preference"];
$file = fopen("./preference.html","w");
fwrite($file, $preference);
fclose($file);
?>
<?php
echo readfile("http://example.com/admin/preference.html"); ?>
这是应该发生的事情。
1
用户打开黑暗模式。
2
存储深色模式。
3
如果暗模式为真,则每个页面都会检查然后使用 PHP echo 作为样式表。
Update 3
<form action="preference.php" method="post">
<input type="checkbox" id="preference" name="preference">
<input type="submit" id="update" name="update" placeholder="Update Preference">
</form>
<?php
if (isset($_COOKIE['darkmode'])) {
if ($_COOKIE['darkmode'] == "true") {
echo '<link rel="stylesheet" href="https://example.com/admin/darkmode.css">';
}
else {
echo '<!--Not Enabled-->';
}
}
?>
我已经为表单添加了代码,可以更新首选项和要添加到每个页面的 echo 函数。我只需要能够将其保存到 cookie。
Update 4
设置页面:
<form action="preference.php" method="post">
<input type="checkbox" id="preference" name="preference">
<input type="submit" id="update" name="update" placeholder="Update Preference">
</form>
首选项.php:
<?php
if (isset($_POST['preference']) {
// If a checkbox is checked in the form, set a cookie
setcookie('isDarkMode', '1');
} else {
// Otherwise -- delete cookie
setcookie('isDarkMode', '', time() - 3600);
}
?>
添加到每个页面:
<? if (isset($_COOKIE['isDarkMode']) && $_COOKIE['isDarkMode']) { ?>
<link rel='stylesheet' type='text/css' href='https://example.com/stylesheet.css'>
<link rel='stylesheet' type='text/css' href='https://example.com/darkmode.css'>
<? } else { ?>
<link rel='stylesheet' type='text/css' href='https://example.com/stylesheet.css'>
<? } ?>
提交表单时,首选项页面显示 500 错误。知道这是为什么吗?
最佳答案
在preference.php
中:
<?
if (isset($_POST['preference'])) {
// If a checkbox is checked in the form, set a cookie
setcookie('isDarkMode', '1');
} else {
// Otherwise -- delete cookie
setcookie('isDarkMode', '', time() - 3600);
}
在每个页面的头文件中:
<html>
<head>
...
<? if (isset($_COOKIE['isDarkMode']) && $_COOKIE['isDarkMode']) { ?>
<link rel='stylesheet' type='text/css' href='darkmode.css'>
<? } else { ?>
<link rel='stylesheet' type='text/css' href='normal.css'>
<? } ?>
...
</head>
关于javascript - 根据用户点击向所有页面添加样式表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54964331/