JS利用Cookie切换网页样式方案
作者:函数茶馆时间:2026-10-30 09:54:13浏览:627
本文介绍了一种使用JavaScript结合Cookie来切换网页样式的方法。通过读取和写入Cookie记录用户选择的主题,实现页面样式的持久化切换,适用于简单的主题切换场景。
JS利用Cookie切换网页样式方案
本文介绍了一种利用JavaScript结合Cookie来切换网页样式的方法。
var styleShow = ["blackgreen", "purple"];
var path = "/";
var StyleSwitch = {
//设置样式
setStyleSheet: function (StyleName) {
var i, a, main;
for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
if (a.getAttribute("rel").indexOf("Style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if (a.getAttribute("title") == StyleName) {
a.disabled = false;
this.setCookie("Style", StyleName);
}
}
}
},
//获取当前使用样式
getStyleSheet: function () {
var i, a;
for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
if (a.getAttribute("rel").indexOf("Style") != -1 && a.getAttribute("title") && !a.disabled) {
return a.getAttribute("title");
}
}
return null;
},
//获取默认样式
getPreferredStyleSheet: function () {
var i, a;
for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
if (a.getAttribute("rel").indexOf("Style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) {
return a.getAttribute("title");
}
}
return null;
},
//获取cookie
getCookie: function (name) {
var cookieName = encodeURIComponent(name) + "=",
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null;
if (cookieStart > -1) {
var cookieEnd = document.cookie.indexOf(";", cookieStart);
if (cookieStart == -1) {
alert(-2);
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
}
for (var i = 0; i < styleShow.length; i++) {
if (cookieValue == styleShow[i]) {
alert(styleShow[i]);
return styleShow[i];
}
}
return styleShow[0];
},
//生成cookie
//name cookie名
//value 值
//expires 过期时间
//path 路径
setCookie: function (name, value, expires, path, domain, secure) {
var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value) + ";";
if (expires instanceof Date) {
cookieText += "expires=" + expires.toGMTString();
}
if (path) {
cookieText += ";path=" + path;
}
if (domain) {
cookieText += ";domain=" + domain;
}
if (secure) {
cookieText += ";secure";
}
document.cookie = cookieText;
},
//重置cookie
unsetCookie: function (name, path, domain, secure) {
this.set(name, "", new Date(0), path, domain, screen);
}
};
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript中json操作技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。
作者最新文章
JS split切割后出现空字符串怎么过滤
2026-11-05 16:00:30
在 React 或 Vue 项目中封装使用 JS 节流防抖
2026-11-05 15:27:29
JavaScript中怎么将带小数的字符串转为整数?
2026-11-05 14:32:38
怎么用JavaScript策略模式重构电商促销计算逻辑?
2026-11-05 14:01:09
JS使用constructor判断数据类型可靠吗
2026-11-05 13:49:41
