如何使用cookie保存页面状态?

时间:2017-12-10 18:20:21

标签: javascript html cookies

所以我的网站上有一个夜间模式功能,下面只是我网站上代码的简短示例。我想知道如何保存页面状态,以便在页面刷新后保持黑暗/浅色。我是用饼干做的吗?我以前从未在我的任何网站上实施过cookies,并且可以真正使用一些帮助。

这是带有按钮的HTML,用于激活脚本:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8"/>

<title>Ryan Simms</title>

</head>

<body>
<script src="scripts/lightSwitch.js"></script> <!-- Loads Script -->

<footer>
    <button type="button" id="lightSwitchOff"></button>
    <button type="button" id="lightSwitchOn"></button>
</footer> <!-- Closes Footer -->

</body>

</html>

这是javascript:

document.addEventListener ("DOMContentLoaded", handleDocumentLoad);

function handleDocumentLoad() {

//Variable
var offSwitch = document.getElementById("lightSwitchOff"); //Targets div with ID lightSwitchOff
var onSwitch = document.getElementById("lightSwitchOn"); //Targets div with ID lightSwitchOn
var style = document.getElementById("pageStyle"); //Targets stylsheet
offSwitch.innerHTML = "Turn On Night Mode";
onSwitch.innerHTML = "Turn Off Night Mode";
onSwitch.style.display = "none";

//Event Listener
offSwitch.addEventListener("click", lightsOff); //When clicked this action is performed
onSwitch.addEventListener("click", lightsOn); //When clicked this action is performed

//Function
function lightsOff() { /*This changes the background colour to black and makes text white*/
    style.setAttribute('href', 'css/darkStyle.css');
    onSwitch.innerHTML = "Turn Off Night Mode";
    onSwitch.style.display = "inline";
    offSwitch.style.display = "none";
}

function lightsOn() { /*This changes the background colour to a white and makes text black*/
    style.setAttribute('href', 'css/lightStyle.css');
    offSwitch.innerHTML = "Turn On Night Mode";
    onSwitch.style.display = "none";
    offSwitch.style.display = "inline";
}
}

1 个答案:

答案 0 :(得分:1)

设置Cookie:

document.cookie = "cookieName=cookieValue";

您还可以指定Cookie应属于的路径。默认为当前页面。

documenet.cookie = "cookieName=cookieValue; path=/folder/";

阅读cookies:

var cookies = document.cookie;

这会将cookies的值设置为长字符串,如:

"cookie1=value1;cookie2=value2"

请注意,您无法访问其他网站的Cookie,而document.cookie只会返回当前域的Cookie。

https://www.w3schools.com/js/js_cookies.asp有一个很好的Cookie教程。

<小时/> 这是一个如何进行解析的示例:

var sugar = document.cookie;
// finds the lights cookie
var start = sugar.indexOf("lights=");
// if there is a light cookie
if (start != -1) {
    // moves the start index to the value of the cookie
    start += "lights=".length;
    // finds the end of the lights cookie value
    var end = sugar.indexOf(";", start);
    var cookieValue;
    // extract the value of the lights cookie
    if (end == -1) {
        cookieValue = sugar.substring(start);
    } else {
        cookieValue = sugar.substring(start, end);
    }

    if (cookieValue == "on") {
        lightsOn();
    } else {
        lightsOff();
    }
}