gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:53:23 24 4
gpt4 key购买 nike

所以我的网站上有夜间模式功能,下面只是我网站上的代码的一个简短示例。我想知道如何保存页面的状态,以便页面刷新后保持暗/亮状态。我用cookie来做这个吗?我以前从未在我的任何网站中实现过 cookie,因此确实需要一些帮助。

这里是 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";
}
}

最佳答案

设置cookie:

document.cookie = "cookieName=cookieValue";

您还可以指定 cookie 所属的路径。默认为当前页面。

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

读取cookie:

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

关于javascript - 如何使用cookie保存页面状态)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47741990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com