我希望保留用户做出的选择,将其保留在cookie中,并在下一次会话中重新使用。
我的cookie运行得很好,但是我不知道如何在下一个会话中使用它。
<element onload="siteversion">
</element>
<script>
var colors = ["#2d2d2d", "#f2f2f2"];
var colorIndex = 0;
function changeColor() {
var col = document.getElementById("body");
if (colorIndex >= colors.length) {
colorIndex = 0;
}
col.style.backgroundColor = colors[colorIndex];
colorIndex++;
// the js script to change the bg color
}
function backgroundHiding() {
console.log('backgroundHiding');
let root = document.documentElement;
var rootElement = document.querySelector(':root');
var rootStyles = getComputedStyle(rootElement);
var mainColor = rootStyles.getPropertyValue('--main-bg');
console.log(mainColor); // '#ffeead'
if (mainColor == "#2d2d2d") {
root.style.setProperty('--main-bg', " url(https://images.unsplash.com/photo-1517524285303-d6fc683dddf8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80)")
document.cookie = "version= ; expires = Thu, 01 Jan 1970 00:00:00 GMT"
document.cookie = "version=light"
} else {
root.style.setProperty('--main-bg', "#2d2d2d")
document.cookie = "version= ; expires = Thu, 01 Jan 1970 00:00:00 GMT"
document.cookie = "version=dark"
}
// the js script to hide my img bg
}
</script>
<script>
var x = document.cookie
function siteversion() {
if (x = dark) {
root.style.setProperty('--main-bg', "#2d2d2d")
} else {
root.style.setProperty('--main-bg', " url(https://images.unsplash.com/photo-1517524285303-d6fc683dddf8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80)")
}
}
</script>
我的浏览器上有cookie,但是刷新页面时,没有为网页选择我的选择(例如深色主题)...
在这里,我创建了一个包含所有代码的堆栈闪电战(因为我只是在上面的脚本中放入了必需的内容)
https://stackblitz.com/edit/typescript-ymgfk2?embed=1&file=index.html