我需要在此脚本中添加Cookie,因此当您点击#full-width或#fixed-width时,它会记住您下次访问时的视图
<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); }
解决方法
我认为饼干有点矫枉过正,并不是真的需要.如果您不必因为未说明的其他各种原因而使用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并提供了一个很好的干净替代Cookies(出于某些目的),但也有它自己的局限性.见here.
需要注意的一件重要事情是切换这样的样式表,你会发现没有样式的内容,而样式表被取出并不是很好.如果您有灵活性,您可能希望使用localstorage附加CSS类并以这种方式更改样式.