2013-07-08 117 views
3

我創建了一個切換菜單,如DEMOCSS轉換toggleClass()後不工作

我爲div.nav-menu添加了一個css過渡效果,並且我使用了max-height:0;max-height:480px;

單擊菜單切換顯示菜單時,轉換效果良好。但是當我點擊菜單切換來再次隱藏菜單時,轉換現在不起作用。

我做錯了什麼?

+1

'請告訴我怎麼了?'哈哈哈哈 – Starx

回答

5

你對CSS轉換錯了。他們在添加或刪除類時不會生成動畫,只會在您更改CSS屬性時生成動畫。 而你直接添加和刪除類。

這裏是您的解決方案:

$('.menu-toggle').on('click', function() { 
    if(nav.hasClass('toggled-on')) { 
     menu.css('maxHeight', 0); 
     //^ Here is changed the 'max-height` first so that the 
     // Transition animation will trigger first 
    } 
    else menu.css('maxHeight', '480px'); 
     //^If not I changed it back to 480px; 
}); 

// Next I bind on the transaction end event of the element to toggle class 
// After it finishes the transistion 

menu.on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function() { 
    nav.toggleClass('toggled-on'); 
}); 

Updated Fiddle

+0

謝謝!但它仍然有問題!因爲您將'max-height = 0;'添加到'.nav-menu',單擊切換隱藏菜單時,樣式仍然存在。所以它只能運行一個循環,而不能繼續循環。 – 85Ryan

+0

謝謝你幫我修改我的問題中的錯誤,我的英文很差! :) – 85Ryan

+0

@ 85Ryan,請看我更新的答案。我更新了你的'nav-menu ul'風格來顯示沒有切換的類,現在一切正常。 :) – Starx

2

還有一個更簡單的方法來獲得你後的效果。

Working Example

JS

$(function() { 
    $('.menu-toggle').click(function(){ 
     if($('.nav-menu').is(':hidden')){ // check to see if menu is hidden 
      $('.nav-menu').slideDown();} // if so slide down 
     else{$('.nav-menu').slideUp();} // else slide up 
    }); 
}); 

CSS

html { 
    font-size: 100%; 
    overflow-y: scroll; 
} 
body { 
    max-width: 860px; 
    margin: 0 auto; 
    font-family: Helvetica, sans-serif; 
} 
.main-navigation { 
    clear: both; 
    min-height: 45px; 
    margin-top: 30px; 
    position: relative; 
} 
.menu-toggle { 
    cursor: pointer; 
    display: inline-block; 
    font: bold 16px/1.3; 
    margin: 0; 
    padding: 10px; 
    color: #fff; 
    background-color: #1e1e1e; 
} 

.nav-menu { 

    margin: 0; 
    background-color: #1e1e1e; 
    display: none; 
    overflow: hidden; 
} 

.nav-menu ul { 
    display: block; 
    margin: 0; 
    padding: 0; 
    width: 100%; 
} 
.nav-menu li { 
    display: block; 
    padding: 10px; 
} 
.nav-menu li a { 
    display: block; 
    padding:10px;color:#fff;line-height:1; 
    text-decoration: none; 
} 
.nav-menu li a:hover,.nav-menu li a:focus{background:#272727;} 
.toggled-on li a:active{background:#2A8A15;} 

API for .slideUp()API for .slideDown()

+1

你明白這個問題是關於CSS轉換嗎? – Starx

+0

@Starx是的,我明白這個問題,只是覺得這個操作可能對同一個目標的捷徑感興趣。此外,您的解決方案似乎只能工作一次......嘗試在隱藏後再次單擊該菜單。 – apaul

+0

你好像對我錯了。我沒有評論你的問題,我的答案是正確的。 :) – Starx