我需要向此脚本添加一个 cookie,以便当您单击 #full-width 或 #fixed-width 时,它会记住您下次访问时的 View
<button id="full-width">GO FULL WIDTH</button>
<button id="fixed-width">GO FIXED WIDTH</button>
$(document).ready(function () {
$("#full-width").click(function () {
$('head').append('<link rel="stylesheet" href="http://www.nitrografixx.com/2015/ladder/full-ladder.css" type="text/css" />');
});
$("#fixed-width").click(function () {
$('link[rel=stylesheet][href="http://www.nitrografixx.com/2015/ladder/full-ladder.css"]').remove();
});
});
我发现这个 cookie 已经在我的网站上用于另一个脚本,但我不知道如何为上面的脚本安装它。
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/; domain=.myfantasyleague.com";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function deleteCookie(name) {
createCookie(name, "", -1);
}
最佳答案
我认为 cookies 对此有点过分了,而且并不是真正需要的。如果您由于未说明的其他各种原因而不必使用 cookie,则可以使用 localStorage
来实现此目的。
https://jsfiddle.net/4bqehjfc/3/
var fullWidth = function() {
$('head').append('<link rel="stylesheet" href="http://www.nitrografixx.com/2015/ladder/full-ladder.css" type="text/css" />');
},
fixedWidth = function() {
$('link[rel=stylesheet][href="http://www.nitrografixx.com/2015/ladder/full-ladder.css"]').remove();
};
$("#full-width").click(function () {
localStorage.setItem('width', 'full-width');
fullWidth();
});
$("#fixed-width").click(function () {
localStorage.setItem('width', 'fixed-width');
fixedWidth();
});
if (localStorage.getItem('width') == 'fixed-width') {
fixedWidth();
} else if (localStorage.getItem('width') == 'full-width') {
fullWidth();
}
重要的一点是:localStorage.setItem()
和localStorage.getItem()
。
localStorage is well supported并提供了 Cookie 的一个干净的替代方案(出于某些目的),但也有其自身的局限性。请参阅here .
需要注意的一件重要事情是,像这样切换样式表,在获取样式表的同时,您将闪烁无样式的内容,这不是很好。如果您有足够的灵 active ,您可能希望使用 localstorage
附加 CSS 类并以这种方式更改样式。
关于jquery - 如何在此脚本中添加 cookie 来缓存样式表更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31107593/