记住用户导航到不同页面时选择的样式表

时间:2012-01-06 15:59:04

标签: javascript html css cookies

我有一个使用不同样式表的网站,用户可以使用此代码选择活动表:

    function setActiveStyleSheet(title) { //title is the title of the link.
   var i, a, main; //i is the index pointer, a is a variable used to store the link statement at i
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) { //gets all the link elements
     if(a.getAttribute("rel").indexOf("style") != -1 // gets the link elements relating to stylesheets
            && a.getAttribute("title")) { //which have the wrong title
                a.disabled = true; //disables the wrong stylesheets
                if(a.getAttribute("title") == title) 
                {
                    a.disabled = false; //if the title of a is equal to the search query, then it is enabled.
                }
     }
   }
}

function changeStyleSheet(sender){
    if (sender == "greythumb")
    {
        setActiveStyleSheet('main');
        document.getElementById(sender).className="selected";
        document.getElementById('redthumb').className="notSelected";
    }
    if (sender == "redthumb")
    {
        setActiveStyleSheet('alternative, red');
        document.getElementById(sender).className="selected";       
        document.getElementById('greythumb').className="notSelected";
    }
}

哪个正常(目前只有两个)

但是,如果用户选择红色CSS,我希望它在用户导航到另一个页面时记住这一点。我记得在某个地方读过这是用cookie完成的,但在我的生活中找不到它,那我该如何实现呢?

干杯

1 个答案:

答案 0 :(得分:2)

这很容易 - http://www.quirksmode.org/js/cookies.html

function createCookie(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=/";
}

function readCookie(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 eraseCookie(name) {
    createCookie(name,"",-1);
}

然后你做

createCookie('stylesheet', 'red', 365);

并使用readCookie

在下一页上阅读
var x = readCookie('stylesheet');
if (x) {
    [ do something with x ]
}