2013-05-17 50 views
1

這裏是我在stackoverflow上的第一篇文章!從cookie中加載CSS類(包含轉換)而不轉換到它們

我已經創建了CSS來在兩種不同的背景顏色之間轉換。

.body { 
    font-family: Tahoma, Geneva, sans-serif; 
    font-size: 20px; 
    font-weight: bold; 
    color: #999; 
     transition: background 5s; 
     webkit-transition: background 5s; 
} 
.bodyclick { 
    background-color:#333 

} 

這是一個照片庫類型的頁面,我喜歡有不同的背景選項來查看圖像。當單擊類「項目名稱」的對象時,我還使用javascript/jQuery在兩種顏色之間切換,並將當前背景狀態存儲在cookie中,以便在瀏覽不同頁面時背景顏色保持不變。

// toggles 'bodyclick' class on the body based on the click of an object with the class projectname and sets the state in a cookie 

$(document).ready(function() { 

    var button = $('.projectname'); 

    //check the cookie when the page loads 
    if ($.cookie('currentToggle') === 'hidden') { 
     toggleBackground(button, false); 
    } 
    else { 
     toggleBackground(button, true); 
    } 

    //handle the clicking of the background (projectname) toggle button 
    button.click(function() { 
     //toggle the background as required, base on current state 
     if ($('.body').hasClass('bodyclick')) { 
      toggleBackground($(this), true); 
     } 
     else { 
      toggleBackground($(this), false); 
     } 
    }); 

}); 

function toggleBackground(button, show) { 

    var background = $('.body'); 

    if (show) { 
     background.removeClass('bodyclick'); 
     $.cookie('currentToggle', '', { path: '/' }); 
    } 
    else { 
     background.addClass('bodyclick'); 
     $.cookie('currentToggle', 'hidden', { path: '/' }); 
    } 
}; 

我現在唯一的問題是,當cookie設置爲暗灰色,刷新或導航到一個單獨的頁面從默認顏色(白色),暗灰色過渡時的頁面加載而不是保持不變。如果我從CSS中移除過渡屬性,它會立即加載到我想要的顏色,但當點擊更改背景時,我喜歡過渡效果。

如果你想查看它生活,你可以訪問這個page

,並點擊,說:「消費後」改變顏色,然後刷新或導航到不同的頁面右下角的文字。

讓我知道如何才能做出這種轉變只有當點擊,而不是頁面加載或如果我需要更好地澄清我的問題。

也作爲一個側面的問題。任何人都可以解釋什麼'隱藏'和'顯示'值在我的JavaScript做?我是編程新手,我從一個stackoverflow帖子中借用代碼,並修改它做我需要的,但我不完全理解這些值是如何工作的。

回答

0

添加和移除覆蓋第一的轉變的第二類:

.no-transition { 
    transition: all 0s !important; 
    -webkit-transition: all 0s !important; 
} 

JS:

background.addClass('no-transition').addClass('bodyclick').removeClass('no-transition'); 
+0

謝謝,這個解決方案有一些調整的工作。我使用.no-transition類,並在加載文檔時使用javascript來添加,然後將它移除。點擊轉換按鈕。 – Constellates