我創建了一個切換菜單,如DEMO。CSS轉換toggleClass()後不工作
我爲div.nav-menu
添加了一個css過渡效果,並且我使用了max-height:0;
到max-height:480px;
。
單擊菜單切換顯示菜單時,轉換效果良好。但是當我點擊菜單切換來再次隱藏菜單時,轉換現在不起作用。
我做錯了什麼?
我創建了一個切換菜單,如DEMO。CSS轉換toggleClass()後不工作
我爲div.nav-menu
添加了一個css過渡效果,並且我使用了max-height:0;
到max-height:480px;
。
單擊菜單切換顯示菜單時,轉換效果良好。但是當我點擊菜單切換來再次隱藏菜單時,轉換現在不起作用。
我做錯了什麼?
你對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');
});
還有一個更簡單的方法來獲得你後的效果。
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;}
'請告訴我怎麼了?'哈哈哈哈 – Starx