我已经建立了一个移动端导航网站,使用jQuery实现slideToggle效果。但是我增加了一些检查,以判断用户是否打开了搜索栏/通知栏,然后显示或隐藏它们,确保在任何时候只有一个项目可见。
我的jQuery代码如下(我也提供了一个Fiddle):
我的jQuery代码如下(我也提供了一个Fiddle):
$(document).ready(function()
{
// Mobile Nav Toggle...
$('.nav-toggle').click(function()
{
// // Check If Other Items Are Open....
if($('.mobile-search-form:visible'))
{
$('.mobile-search-form').hide();
}
// // Check If Other Items Are Open....
if($('.mobile-notifications:visible'))
{
$('.mobile-notifications').hide();
}
$('nav').slideToggle();
accordion_links();
return false;
})
// Add a Chevron Class To Links (For Mobile Nav)...
$(function() {
$('nav ul li a').each(function()
{
if ( $(this).parent('li').children('ul').size() > 0 )
{
$(this).addClass('chevron-down');
}
});
});
function accordion_links()
{
$('.chevron-down').click(function()
{
$(this).next('ul.sub-nav').slideToggle();
if($(this).parent('li').hasClass('open'))
{
$(this).removeClass('chevron-up');
$(this).addClass('chevron-down');
$(this).parent('li').removeClass('open');
}
else
{
$(this).removeClass('chevron-down');
$(this).addClass('chevron-up');
$(this).parent('li').addClass('open');
}
})
}
// Toggle Search Form (On Mobile)....
$('.search-link').click(function()
{
// Check If Notifications / Search Form Are Visible...
if($('nav:visible'))
{
$('nav').slideUp();
}
if($('.mobile-notifications:visible'))
{
$('.mobile-notifications').hide();
}
$('.mobile-search-form').slideToggle();
return false;
})
// Toggle Notifications On Mobile...
$('a.notifications').click(function()
{
// Check If Notifications / Search Form Are Visible...
if($('nav:visible'))
{
$('nav').hide();
}
if($('.mobile-search-form:visible'))
{
$('.mobile-search-form').hide();
}
$('.mobile-notifications').slideToggle();
return false;
})
// Close Notification Block
$('.close-notification').click(function()
{
$('.notification').fadeOut();
})
})
我遇到的问题是,切换按钮第一次可以正常工作,但当你点击搜索链接后,会加载导航。然后slideToggle尝试两次执行动画(打开和关闭)。
这里有一个jsFiddle:链接
为什么会出现这种情况?我只能假设我的逻辑有误。
$('.mobile-search-form:visible')
总是为真值,您需要检查$('.mobile-search-form:visible').length
属性。 - Satpal