用于记录整个站点的用户首选项的Cookie或会话变量

时间:2016-02-07 20:44:09

标签: javascript cookies

我尝试设置Cookie或会话变量以使网站上的用户首选项保留在网站的每个页面上,并且我尝试使用Javascript进行操作,但是我是开放尝试任何有效的代码。

我想让我的onclick用户选项在网站的每个页面上为用户保持活动状态。因此,如果他们导航到第2页,则会记住他们从第1页开始选择布局并在第2页保持活动状态。

我所构建的基本上是网站上的电子阅读器,因此我希望用户能够更改字体大小,更改背景颜色并更改文本宽度以适合他们的偏好。我已经完成了所有工作,但是当他们点击下一页时,设置清晰,他们必须再次设置它们。我希望网站能够记住他们在网站上的整个会话或一段时间的选择,即使这是可能的。

我对Javascript很新(这是我写作的第一天),所以下面的代码可能会非常糟糕。

我不知道我是否需要使用Cookie或会话变量,但我发现的所有修复程序都不起作用,或者它们并非真正意味着这个目的,所以我不能使用它们。

在代码中,我创造了“故事”中的所有内容。当用户点击其上方的选项时,div会更改,选项为:

  • 放大字体
  • 收缩字体
  • 黑暗主题
  • 光明主题
  • 棕褐色主题
  • 全宽
  • 75%宽度
  • 50%宽度

到目前为止一切都有效,但如果用户导航到另一个页面,我就无法坚持使用。他们点击下一页时,他们的偏好清晰,这就是问题。

这是我现在的代码。

HTML:

 <html>
 <head>
  <title>Test</title>
  <script type="text/javascript" src="cookies.js"></script>
  <script type="text/javascript" src="customize.js"></script>

 <style>
.text-tools{margin:auto; text-align:center;}
 </style>
 </head>
 <body>
 <div class="text-tools">
<img id="plustext" alt="Increase text size" src="images/A-plus.png" onclick="resizeText(1)" style="width:25px;" />
<img id="minustext" alt="Decrease text size" src="images/A-minus.png" onclick="resizeText(-1)" style="width:25px;" />
<a href="#" onclick="dark()"><img src="images/dark.png" style="width:25px;" /></a>
<a href="#" onclick="light()"><img src="images/light.png" style="width:25px;" /></a>
<a href="#" onclick="sepia()"><img src="images/sepia.png" style="width:25px;" /></a>
<a href="#" onclick="full()"><img src="images/full.png" style="width:25px;" /></a>
<a href="#" onclick="third()"><img src="images/third.png" style="width:25px;" /></a>
<a href="#" onclick="half()"><img src="images/half.png" style="width:25px;" /></a>
</div>
<div id="story">
<div id="sfont">
<div id="sbg">
<div id="stext">
<h1 id="chtitle">The Title</h1>
<p style="font-size:1em;font-color:#000;"><span id="cap1" style="font-size:2em;">S</span>ome text goes here...</p>
<a href="page2.html">Page Two</a>
</div>
</div>
</div>
</div>
<p>Other stuff here</p>

 </body>
</html>

自定义Javascript:

    // Change font size
function resizeText(multiplier) {
  if (document.getElementById("sfont").style.fontSize == "") {
    document.getElementById("sfont").style.fontSize = "1.0em";
  }
  document.getElementById("sfont").style.fontSize = parseFloat(document.getElementById("sfont").style.fontSize) + (multiplier * 0.2) + "em";
}

//Change background color
<!--//

function dark()

{
document.getElementById("sbg").style.backgroundColor="#474747"
document.getElementById("stext").style.color="#cdcdcd"
document.getElementById("chtitle").style.color="#e5e5e5"
document.getElementById("cap1").style.color="#e5e5e5"
}

function light()

{
document.getElementById("sbg").style.backgroundColor="#ffffff"
document.getElementById("stext").style.color="#8C9398"
document.getElementById("chtitle").style.color="#686868"
document.getElementById("cap1").style.color="#686868"
}

function sepia()

{
document.getElementById("sbg").style.backgroundColor="#c1b29b"
document.getElementById("stext").style.color="#77674f"
document.getElementById("chtitle").style.color="#564a36"
document.getElementById("cap1").style.color="#564a36"

}

//Change div width
function full()

{
document.getElementById('story').setAttribute("style","width:100%;margin:auto");
}

function third()

{
document.getElementById('story').setAttribute("style","width:75%;margin:auto");
}

function half()

{
document.getElementById('story').setAttribute("style","width:50%;margin:auto");
}

//-->

这是不起作用的Cookie Javascript:

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

我很确定我没有正确使用cookies.js,但我无法弄清楚如何让它发挥作用。

任何有关修复cookies.js的帮助,以便它可以工作或替代方法真的很有帮助。

提前感谢任何想要解决这个问题的人。

2 个答案:

答案 0 :(得分:0)

我试用了你的Cookie Javascript,它运行正常 如果您希望用户选项在网站的每个网页上保持活动状态,则可能需要考虑使用sessionStorage

您的自定义Javascript正在运行,尽管语法错误。

我的建议是在设置用户选项时保存用户选项,然后在之后加载的每个页面中读取它们。

这是您需要的自定义Javascript。我还纠正了语法。我会在这种情况下使用sessionStorage,因为这样你不需要cookie。

window.onload = loadSettings;
// Change font size
function resizeText(multiplier) {
    sessionStorage.setItem("fontSize", multiplier);
    if (document.getElementById("sfont").style.fontSize == "") {
        document.getElementById("sfont").style.fontSize = "1.0em";
    }
    document.getElementById("sfont").style.fontSize = parseFloat(document.getElementById("sfont").style.fontSize) + (multiplier * 0.2) + "em";
}

function dark() {
    sessionStorage.setItem("background", "dark");
    document.getElementById("sbg").style.backgroundColor = "#474747";
    document.getElementById("stext").style.color = "#cdcdcd";
    document.getElementById("chtitle").style.color = "#e5e5e5";
    document.getElementById("cap1").style.color = "#e5e5e5";
}

function light() {
    sessionStorage.setItem("background", "light");
    document.getElementById("sbg").style.backgroundColor = "#ffffff";
    document.getElementById("stext").style.color = "#8C9398";
    document.getElementById("chtitle").style.color = "#686868";
    document.getElementById("cap1").style.color = "#686868";
}

function sepia() {
    sessionStorage.setItem("background", "sepia");
    document.getElementById("sbg").style.backgroundColor = "#c1b29b";
    document.getElementById("stext").style.color = "#77674f";
    document.getElementById("chtitle").style.color = "#564a36";
    document.getElementById("cap1").style.color = "#564a36";
}

//Change div width
function full() {
    sessionStorage.setItem("divWidth", "full");
    document.getElementById('story').setAttribute("style", "width:100%;margin:auto");
}

function third() {
    sessionStorage.setItem("divWidth", "third");
    document.getElementById('story').setAttribute("style", "width:75%;margin:auto");
}

function half() {
    sessionStorage.setItem("divWidth", "half");
    document.getElementById('story').setAttribute("style", "width:50%;margin:auto");
}

function loadSettings() {
    var fontSize = sessionStorage.getItem("fontSize") && parseFloat(sessionStorage.getItem("fontSize"));
    var background = sessionStorage.getItem("background") && sessionStorage.getItem("background");
    var divWidth = sessionStorage.getItem("divWidth") && sessionStorage.getItem("divWidth");
    resizeText(fontSize);
    if (background == "dark") dark();
    else if (background == "light") light();
    else if (background == "sepia") sepia();
    if (divWidth == "full") full();
    else if (divWidth == "third") third();
    else if (divWidth == "half") half();
}

答案 1 :(得分:0)

我会使用localStorage来保存信息。每次发出HTTP请求时,Cookie都会将信息发送到服务器,例如获取新页面。此外,他们不会保存尽可能多的信息。 w3schools has a page on localStorage and sessionStorage可能值得一看。

为了尽可能少地修改你的代码,我建议你定义一个新函数,它存储调用它们的函数,然后调用它们。

function update(key, funct) {
    localStorage.setItem(key, funct);
    window[funct].call();
}

您需要更改链接:

<a href="#" onclick="update('color','dark')">...
<a href="#" onclick="update('color','light')">...
<a href="#" onclick="update('color','sepia')">...
<a href="#" onclick="update('size','full')">...
<a href="#" onclick="update('size','third')">...
<a href="#" onclick="update('size','half')">...

加载新页面时,您可以检查给定的设置是否已更改,并调用该函数执行给定的更改。

if (funct = localStorage.getItem('color')) {
    window[funct].call();
}
if (funct = localStorage.getItem('size')) {
    window[funct].call();
}

最好是在循环中执行此操作:

var functs = ['color', 'size'];
for (var i=0; i < functs.length; i++) {
    if (funct = localStorage.getItem(functs[i])) {
        window[funct].call();
    }
}

要查看工作示例,请将以下代码保存到网络服务器中的html文件中,然后将其加载到网络浏览器中:

<!DOCTYPE html>
<html lang="en">
<head>
    <script>

    // Define fuctions: dark, light, etc. so that they just print their names
    var fs = ['dark', 'light', 'sepia', 'full', 'third', 'half']
    for (var i=0; i < fs.length; i++) {
        var f = fs[i];
        window[f] = (function(funct) {
            return function() {
                alert(funct);
            }
        })(f)
    }

    // Update localStorage and call function
    function update(key, funct) {
        localStorage.setItem(key, funct);
        window[funct].call();
    }

    // Page has loaded
    document.addEventListener("DOMContentLoaded", function() {

        // Call functions when page is loaded
        var functs = ['color', 'size'];
        for (var i=0; i < functs.length; i++) {
            if (funct = localStorage.getItem(functs[i])) {
                window[funct].call();
            }
        }
    });
    </script>
</head>
<body>
    <a href="#" onclick="update('color','dark')">dark</a>
    <a href="#" onclick="update('color','light')">light</a>
    <a href="#" onclick="update('color','sepia')">sepia</a><br>
    <a href="#" onclick="update('size','full')">full</a>
    <a href="#" onclick="update('size','third')">third</a>
    <a href="#" onclick="update('size','half')">half</a>
</body>
</html>

如果您使用控制台进行调试,我建议您将代码中的alert更改为console.log。它不那么具有侵入性。