2012-01-06 30 views
1

我有一個網站,它使用不同的樣式表,用戶可以從中使用此代碼選擇活動工作表用戶已選擇:記住它的樣式表,當他們瀏覽到不​​同的頁面

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完成的,但是在我的生活中找不到它,那麼我該如何實現呢?

乾杯

回答

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 ] 
} 
相關問題