【问题标题】:Remember which style sheet a user has selected when they navigate to different pages记住用户在导航到不同页面时选择了哪个样式表
【发布时间】:2012-01-07 00:03:53
【问题描述】:

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

    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 完成的,但我一辈子都找不到它,那么我应该如何实现呢?

干杯

【问题讨论】:

    标签: javascript html css cookies


    【解决方案1】:

    这很容易 - 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 ]
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多