如何在此脚本中添加cookie以缓存样式表更改

时间:2015-06-29 04:03:22

标签: jquery

我需要在此脚本中添加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);
}

3 个答案:

答案 0 :(得分:4)

我认为饼干有点矫枉过正,并不是真的需要。如果您因为其他各种原因而不必使用cookie,则可以使用localStorage这样做。{/ p>

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

需要注意的一件重要事情就是切换这样的样式表,你会发现没有样式的内容,同时提取的样式表并不是很好。如果您有灵活性,可以使用localstorage附加CSS类并以这种方式更改样式。

答案 1 :(得分:0)

考虑到这一点:

  

HTMLStyleElement.disabled

     

是布尔值,如果禁用样式表,则为true,如果为false   如果没有。

source)您可以执行以下操作:

<style id="first" disabled >@import url(/a.css);</style>
<style id="second" >@import url(/b.css);</style>

和代码:

$("#first-on").click(function () {
  $("#second")[0].disabled = true;
  $("#first")[0].disabled = false;
});

答案 2 :(得分:0)

如果您使用localStorage遇到某些已知问题,下面的示例将使用您提供的Cookie函数。

请注意,我们将避免在此处使用jQuery作为代码的初始部分,以减少/删除有人将布局Cookie设置为全宽时可能遇到的初始闪存。

我也稍微升级了你的按钮:)

<!doctype html>
<html>
<head>
    <title>Cookiesheet</title>

    <script>
    var layoutcookiename = 'layout_cookie'; //just in case you want to rename the cookie for your layout
    var layoutcookiedays = 30; //how many days do you want the cookie to last for
    var mycookiedomain = '.nitrografixx.com';  //add a period in front of your domain name here to include it for all subdomains

    var layoutcookie = getCookie(layoutcookiename); //Get the stored cookie if any

    //Assuming the default layout will be fixed width
    var currentlayout = (layoutcookie === null || layoutcookie === 'fixed') ? 'fixed' : 'full';
    //If default is to be full width, uncomment and use this if statement instead of the preceding line
    //var currentlayout = (layoutcookie === null || layoutcookie === 'full') ? 'full' : 'fixed';

    if (currentlayout === 'full') {
        document.write('<link rel="stylesheet" href="http://www.nitrografixx.com/2015/ladder/full-ladder.css" type="text/css" />');
    }

    //We only need the function to get cookies up here
    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;
    }
    </script>
</head>
<body>

<!-- Dynamic button text for initial load -->
<button id="layout-switch"><script>if (currentlayout === 'fixed') { document.write('GO FULL WIDTH'); } else { document.write('GO FIXED WIDTH'); }</script></button>

<!-- The rest of the javascript that can occur on document ready -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $('#layout-switch').click(function () {
        if (currentlayout === 'fixed') {
            $('head').append('<link rel="stylesheet" href="http://www.nitrografixx.com/2015/ladder/full-ladder.css" type="text/css" />');
            $(this).html('GO FIXED WIDTH');
            currentlayout = 'full';
        } else {
            $('link[rel=stylesheet][href="http://www.nitrografixx.com/2015/ladder/full-ladder.css"]').remove();
            $(this).html('GO FULL WIDTH');
            currentlayout = 'fixed';
        }

        setCookie(layoutcookiename, currentlayout, layoutcookiedays);
    });
});

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=" + mycookiedomain;
}

function deleteCookie(name) {
    createCookie(name, "", -1);
}
</script>
</body>