javascript - 如何将 css 文件插入其中而不是声明颜色

标签 javascript php css cookies themes

我有一个主题更改的工作PHP,附加了一个cookie,当用户离开网站时它会记住主题颜色。但我需要将其更改为 javascript,并且仍然利用 CSS 文件。我该怎么做?

这是我的 php 文件

<html>
  <head>
    <?php
      //GET method to retrieve the theme for the user
      if (isset($_GET["theme"])) {
        if ($_GET["theme"] == 'blue') {
          // set theme to be blue by default unless the user has selected red or 
          yellow theme then change
          // once user has selected theme browser will remember for 1 year
          setcookie("theme", "blue", strtotime('+1 year'));
        } else if ($_GET["theme"] == 'red') {
          setcookie("theme", "red", strtotime('+1 year'));
        } else if ($_GET["theme"] == 'yellow') {
          setcookie("theme", "yellow", strtotime('+1 year'));
        }
        header("Location: index.php");
      }
      /* once user logs out. session is to rememebr the color chosen as above,
         logging out to location index.php */
      if (isset($_GET["logout"]) && $_GET["logout"] == 'true') {
        session_destroy();
        header("Location: index.php");
        die;
      }

      // use theme cookie 
      if (isset($_COOKIE["theme"])) {
        if ($_COOKIE["theme"] == "yellow") {
          /* if yellow theme is selected use stylesheet yellow
             otherwise if not select */
          red style sheet
          echo '<link rel="stylesheet" type="text/css" href="styles/styleyellow.css">';
        } else if ($_COOKIE["theme"] == "red") {
          echo '<link rel="stylesheet" type="text/css" href="styles/stylered.css">';
        } else {
          /* if yellow or red were not selected
             then set to default blue stylesheet theme */
          echo '<link rel="stylesheet" type="text/css" href="styles/styleblue.css">';
        }
      } else {
        echo '<link rel="stylesheet" type="text/css" href="styles/styleblue.css">';
      }
    ?>
  </head>
  <body>
    <?php
      /* once the user has logged in
         this shows options for the user to change theme colors. */
      if (isset($_SESSION["username"])) {
        echo '<div id="theme">';
        echo 'Set a Theme:<br>';
        echo '<a href="index.php?theme=blue">Blue (Default)</a><br>';
        echo '<a href="index.php?theme=red">Red</a><br>';
        echo '<a href="index.php?theme=yellow">Yellow</a><br>';
        echo '</div>';
      }
    ?>
  </body>
</html>

最佳答案

有警告

要让 JavaScript 访问 cookie,它们必须设置为 httponly=false (默认)。请参阅PHP.net更多细节;这是基础知识:

httponly
When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript.

JS 将无法读取任何先前使用 httponly=true 设置的 cookie .

页面加载

JavaScript 无法在加载前准备好页面;它只能对浏览器解析后的内容起作用。

  • 我们需要做的第一件事是监视 readyState document的;我们需要它至少为 "interactive"然后我们才能设置新内容或更改现有内容。由于我们需要添加新的 stylesheet根据用户设置,我们必须等待浏览器理解DOM在尝试插入之前。

  • 接下来我们需要检索已为该站点设置的 cookie(如果有)。 document.cookie 返回以分号分隔的字符串 key=value对。我们需要解析该字符串以查找其中之一是否是“主题”,如果是,则获取其 value .

  • 如果之前没有设置 cookie,并且没有查询字符串给我们 theme=<color> ,我们需要默认为“蓝色”,并附加 <link>document<head> 。我们可以使用 XMLHTTPRequest 对于资源并添加 responseText <style>元素,但在这种情况下,额外的工作不会带来任何好处。

  • 现在我们已将样式表设置为适当的颜色,下次只需设置或更新 cookie。

此脚本处理上面 PHP 完成的大部分工作,但与登录或注销、更改位置或设置任何 HTML 无关。

只需将其添加到 <script> <head> 中的元素您希望执行这些操作的文档,您应该可以开始了。

如有任何不明白的地方,请随时询问,或者如果有任何问题无法按预期工作,请告诉我;我很乐意跟进编辑和/或讨论以提供帮助。

( function( W, D ) {
    "use strict";
    const init = function() {
        var cookie_string = D.cookie,
            query_theme = /theme\=([a-z]+)/.exec( location.search ),
            style_sheet = D.createElement( "link" ),
            date = new Date,
            theme;
        if ( cookie_string ) {
            var cookie_array = cookie_string.split( ";" ), vs;
            cookie_array.forEach( function( v ) {
                vs = v.trim().split( "=" );
                if ( vs[ 0 ] === "theme" ) {
                    theme = vs[ 1 ];
                }
            } );
        }
        // prioritize: query string > cookie > default
        theme = !!query_theme ? query_theme[ 1 ] : theme || "blue";
        // add the stylesheet
        style_sheet.href = "styles/style" + theme + ".css";
        style_sheet.type = "text/css";
        style_sheet.rel = "stylesheet";
        D.querySelector( "head" ).appendChild( style_sheet );
        // set/update the cookie
        date.setDate( date.getDate() + 365 );
        D.cookie = "theme=" + theme +
            "; expires=" + date.toString().replace( /\+.*$/, "" );
    };
    if ( /^(?:interactiv|complet)e$/.test( D.readyState ) ) {
        init();
    } else {
        W.addEventListener( "DOMContentLoaded", init, false );
    }
} ( window, document ) );

使用 localStorage API

  • localStorage不会过期,因此不需要像 cookie 那样处理日期。

  • localStorage 可供浏览器访问;提供内容的服务器将无权访问这些值,除非这些值被显式传递给它。通过关注相对 .css 的请求,服务器可以隐式知道正在使用哪个主题。来自这个 PHP session 。

如果查询字符串中存在主题值,这将优先考虑主题值,如果不存在,将检查 localStorage对于“主题”字符串,如果找不到,将使用默认字符串“blue”。

( function( W, D ) {
    "use strict";
    const init = function() {
        var style_sheet = D.createElement( "link" ),
            query_theme = /theme\=([a-z]+)/.exec( location.search ),
            // prioritize: query string > localStorage > default
            theme = !!query_theme ? query_theme[ 1 ] :
                W.localStorage.getItem( "theme" ) || "blue";
        // set the current theme in localStorage
        W.localStorage.setItem( "theme", theme );
        // add the stylesheet
        style_sheet.href = "styles/style" + theme + ".css";
        style_sheet.type = "text/css";
        style_sheet.rel = "stylesheet";
        D.querySelector( "head" ).appendChild( style_sheet );
    };
    if ( /^(?:interactiv|complet)e$/.test( D.readyState ) ) {
        init();
    } else {
        W.addEventListener( "DOMContentLoaded", init, false );
    }
} ( window, document ) );

localStorage API有个妹妹 sessionStorage 用于临时存储 session 数据。

两者localStoragesessionStorage可存储 stringyfied JSON 因此,处理复杂数据比 cookie 容易得多。

关于javascript - 如何将 css 文件插入其中而不是声明颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44602595/

相关文章:

html - 仅向内容添加滚动,而不是标题

javascript - 无需大量剪切和粘贴的多张幻灯片

javascript - 元素特定区域的背景颜色

php - 当 POST 数组*不*为空时,RESTful 服务会出错

javascript - 用于将图片插入工作表(Google 应用程序脚本)的 blob 大小是否有限制?

php - 获取嵌套关联数组中所有元素的路径和值

javascript - 我如何接收带有 PHP 附加文件和字符串的 FormData?

HTML CSS justify 技巧不能与 angularJS 结合使用

javascript - 带有流量路由器的 meteor : Do I have access to Meteor. 来自流量路由器触发器的用户?

javascript - JQuery datetimepicker 异常日与 minDate 和 maxDate