Reprinted: https://www.cnblogs.com/maderlzp/p/7843365.html
As shown below:
Requirements: When you select a radio button top right corner of the color values theme burst navigation bar change to the selected color, refresh the page before the time when, the selected color still selected off color;
cookie's main role:
Cookie is mainly used in the following three aspects:
- Session state management (such as user login status information, shopping cart, game scores and other records required)
- Personalized settings (such as user-defined settings, themes, etc.)
- Browser behavior tracking (such as tracking user behavior analysis)
/**
* 2, change the color of the navigation bar head
*/
$(
'.theme_color_checkbox li').
on(
'click',
function () {
$(
this).
addClass(
'icondagou').
siblings().
removeClass(
'icondagou');
var
inputIndex =
$(
this).
index();
//获取到选中颜色的下标
$(
'.header_wrap .nav').
attr(
'class',
'nav color_label_' + (
inputIndex +
1));
// localStorage.setItem('themeColor', inputIndex);
setCookie(
'themeColorCookie',
inputIndex,
7);
//设置7天之后过期
})
// var ThemeColorIndex = localStorage.getItem('themeColor');
var
ThemeColorIndex =
getCookie(
'themeColorCookie');
if (
ThemeColorIndex) {
let
nav =
ThemeColorIndex +
1;
$(
'.theme_color_checkbox li').
eq(
ThemeColorIndex).
addClass(
'icondagou').
siblings().
removeClass(
'icondagou');
$(
'.header_wrap .nav').
attr(
'class',
'nav color_label_' + (
ThemeColorIndex *
1 +
1));
}
/**
*
*
@param
{*}
name
//cookie的名称
*
@param
{*}
value
//cookie的值
*
@param
{*}
day
//cookie的过期时间
*/
function
setCookie(
name,
value,
day) {
if (
day !==
0) {
var
expires =
day *
24 *
60 *
60 *
1000;
//转化为秒
var
date =
new
Date(+
new
Date() +
expires);
document.
cookie =
name +
'=' +
value +
';expires=' +
date.
toUTCString();
}
else {
document.
cookie =
name +
"=" +
escape(
value);
}
}
/**
*
*
@param
{*}
name
//cookie的名称
*/
function
getCookie(
name) {
var
arr;
var
reg =
new
RegExp(
"(^| )" +
name +
"=([^;]*)(;|$)");
/**
* ^:匹配输入字符串的开始位置
* (^| );//匹配cookie开头或者空格(cookie键值对之间用分号空格隔开)===>cookie键值对的开始
* name:cookie的名字
* (
[
^;
]
*):匹配cookie中除了分号(;)以外的值
* (;|$):匹配cookie中分号或者匹配cookie的结尾位置
*
*/
if (
arr =
document.
cookie.
match(
reg)) {
return
unescape(
arr[
2]);
//unescape :是对escape的解码
}
else {
return
null;
}
}
/**
*
*
@param
{*}
name
//删除cookie的值
*/
var
delCookie =
function (
name) {
setCookie(
name,
'', -
1);
}
/**
* cookie设置基本语法:
* cookieName=cookieValue ===> cookieName(cookie名字),cookieValue(cookie值)
* expires=Sun, 13 Oct 2019 02:09:08 GMT ===> 设置cookie过期日期,若未定义,cookie会在会话结束时候过期,日期格式为new Date().toUTCString()
* path=/demoDir ===> 设置文件的路径,没有定义默认为当前文档位置的路径
* domain=127.0.0.1 ===> 设置指定域名,若未定义,默认问当前文档位置的路径或域名的部分
* max-age=604800000 ===> 设置文档被查看后cookie过期时间,单位为秒
* secure=true ===> cookie只会被https传输,即加密的https链接传输
*/
// document.cookie = "cookieName=cookieValue;expires=Sun, 13 Oct 2019 02:09:08 GMT;path=/demoDir;domain=127.0.0.1;max-age=604800000;secure=true";