我有以下代码,可以在切换点击图标(#burger)时打开和关闭响应式菜单(#burger-nav)。菜单选项跳转到同一HTML页面中的锚点,但菜单保持打开状态。
如何在点击选项时关闭响应式菜单,以便当用户返回页面顶部时,菜单将以原始状态关闭?
$(document).ready(function(){
// ----- Responsive menu -----
( function( $ ) {
/* Run this code when the #mob-nav-toggle link has been tapped or clicked */
$( '#burger' ).on( 'touchstart click', function(e) {
e.preventDefault();
var $body = $( 'body' ),
$page = $( '#wrapper' ),
$menu = $( '#burger-nav' ),
/* Cross browser support for CSS "transition end" event */
transitionEnd = 'transitionend webkitTransitionEnd otransitionend MSTransitionEnd';
/* When the toggle menu link is clicked, animation starts */
$body.addClass( 'animating' );
/* Determine the direction of the animation and add the correct direction class depending on whether the menu was already visible. */
if ( $body.hasClass( 'menu-visible' ) ) {
$body.addClass( 'up' );
} else {
$body.addClass( 'down' );
}
/* When the animation (technically a CSS transition) has finished, remove all animating classes and either add or remove the "menu-visible" class depending whether it was visible or not previously. */
$page.on( transitionEnd, function() {
$body
.removeClass( 'animating down up' )
.toggleClass( 'menu-visible' );
$page.off( transitionEnd );
} );
} );
} )( jQuery );
HTML:
<div id="wrapper">
<header>
<nav id="burger-nav">
<ul>
<li><a href="" title="">parent link</a>
<ul>
<li><a href="#bookmark" title="">link</a></li>
<li><a href="#bookmark" title="">link</a></li>
<li><a href="#bookmark" title="">link</a></li>
<li><a href="#bookmark" title="">link</a></li>
</ul>
</li>
<li><a href="" title="">parent link</a></li>
<li><a href="" title="">parent link</a></li>
<li><a href="" title="">parent link</a></li>
</ul>
</nav>
</header>
</div>
答案 0 :(得分:0)
将您的匿名事件处理函数更改为命名函数: 然后,您可以在单击汉堡包按钮或菜单项链接
时调用它(function ($) {
function menuToggle(e) {
e.preventDefault();
var $body = $('body'),
$page = $('#wrapper'),
$menu = $('#burger-nav'),
/* Cross browser support for CSS "transition end" event */
transitionEnd = 'transitionend webkitTransitionEnd otransitionend MSTransitionEnd';
/* When the toggle menu link is clicked, animation starts */
$body.addClass('animating');
/* Determine the direction of the animation and add the correct direction class depending on whether the menu was already visible. */
if ($body.hasClass('menu-visible')) {
$body.addClass('up');
} else {
$body.addClass('down');
}
/* When the animation (technically a CSS transition) has finished, remove all animating classes and either add or remove the "menu-visible" class depending whether it was visible or not previously. */
$page.on(transitionEnd, function () {
$body
.removeClass('animating down up')
.toggleClass('menu-visible');
$page.off(transitionEnd);
});
$(document).ready(function () {
// ----- Responsive menu -----
/* Run this code when the #mob-nav-toggle link has been tapped or clicked */
$('#burger').on('touchstart click', menuToggle);
$('#burger-nav').on('touchstart click', 'a', menuToggle);
});
}}
)(jQuery);