提问者:小点点

根据用户单击将样式表添加到所有页面


这个想法是在网站上有一个设置页面,可以通用地改变主题。因此设置页将包含此链接;

null

<a href="">Click here to enable dark mode</a>

null

单击此按钮将为每个页面添加另一个样式表。

null

<?php echo "<link rel='stylesheet' type='text/css' href='darkmode.css'>"; >

null

这就是我们的想法,站点已经构建好,添加darkmode.css就会在页面上显示暗模式。

我对其他的想法持开放态度,比如设置一个简单的cookie,并且只有当样式表为true时才激活。我不想在每一个页面上切换,因为这意味着手动编辑所有的页面,而且它只对某些用户可用。

我假设一个变量必须在设置页面上设置为true,但它需要在整个站点上传递,所以

null

<?php
if ($darkmode = $true)
  echo "<link rel="stylesheet" href="https://example.com/darkmode.css">";
?>

null

我想这样的东西需要添加到每一个页面上,如果是真的,那么只需要附和样式就可以了?

如果有任何帮助,我们将不胜感激。

更新1

这些代码都不起作用,但它只是一个示例。管理员会选择一个复选框,如果选中了复选框,页面就会读取文件中的Yes/No,然后回显到附加样式表的链接。

null

<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"); ?>

null

那是应该发生的。1用户打开暗模式。存储2暗模式。3如果暗模式为true,则每个页面检查样式表,然后使用PHP echo。

更新3

null

<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-->';
   }
   }
?>

null

我已经为表单添加了代码,该表单将更新首选项和echo函数,以添加到每个页面。我只需要能把它留到一块饼干里。

更新4

设置页:

null

<form action="preference.php" method="post">
 <input type="checkbox" id="preference" name="preference">
 <input type="submit" id="update" name="update" placeholder="Update Preference">
 </form>

null

preference.php:

null

<?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);
}
?>

null

添加到每一页:

null

<? 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'>
  <? } ?>

null

在提交表单时,首选项页面显示500错误。知道为什么会这样吗?


共1个答案

匿名用户

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>