单击以关闭移动设备上的jQuery下拉菜单,同时保留其他行为 [英] Click to close jQuery dropdown menu on mobile devices while retaining other behavior
问题描述
我有一个非常简单的jQuery下拉菜单,其中的链接具有通常的ul/li列表排列方式.下拉菜单的代码如下:
I have a pretty simple jQuery dropdown menu with links in the usual ul/li list arrangement. The code for the dropdown is as follows:
$('body').ready(function() {
if(screen.width <= 720) {
$('.dropdown').hover(function() { $(this).find('.subMenu').toggle(); });
$('.dropdown').click(function() { if( $('this').css('display') != 'none') {
$('this').toggle();
}
});
}
else
{
$('.dropdown').hover(
function() { $(this).stop(true,true).find('.subMenu').slideDown("fast"); },
function() { $(this).stop(true,true).find('.subMenu').hide(); }
);
}
});
在移动设备上(忽略720宽度,仅用于测试),我想实现以下功能:
On mobile devices (ignore the 720 width, it's just for testing right now), I would like to achieve the following functionality:
-
用户点击带有下拉菜单的链接>如果打开菜单,则将其关闭
User taps link with a dropdown menu > If menu is open, close it
当另一个菜单已经打开时,用户点击链接>关闭上一个菜单,打开当前菜单
User taps link while another menu is already open > Close previous menu, open current menu
我发现悬停功能实际上可以处理#2和#3,但是我不知道如何使#1正常工作.我可以肯定地说,我知道为什么要这样做
I found that the hover function actually handles #2 and #3, but I can't figure out how to get #1 working. I'm fairly certain that I know why this particular attempt
$('.dropdown').click(function() { if( $('this').css('display') != 'none') {
$('this').toggle();
}
});
失败.我猜想单击(在这种情况下为点击)会触发悬停事件,该事件似乎优先,因此显示菜单而不是隐藏菜单.
fails. I'm guessing that the click (or tap, in this case) triggers the hover event, which seems to take precedence and therefore displays the menu, instead of hiding it.
如何在移动设备上使用它?
How can I get this working on mobile devices?
我正在使用jQuery v1.7.2
I'm using jQuery v1.7.2
HTML列表结构如下所示,以防它对某人有所帮助(删节版):
HTML list structure is as follows, in case it helps someone (abridged version):
<div id="navbar">
<ul>
<li class="dropdown"><a href="#">Link A</a></li>
<li class="dropdown"><a href="#">Link B</a>
<ul class="subMenu">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</li>
</ul>
</div>
推荐答案
If you use jq 1.7+ then try this DEMO HERE http://jsfiddle.net/SCN5T/3/
$(function(){
$(document).mousedown(function(){
$('.dropdown .active').removeClass('active').children('ul').hide();
})
$('.dropdown').on('mousedown','.subMenu', function(e){
e.stopPropagation();
var elem = $(this);
if(elem.is('.active')) {
elem.children('ul').slideUp(150);
elem.removeClass('active');
} else {
$('.dropdown .active').removeClass('active').children('ul').hide();
elem.addClass('active').children('ul').slideDown(150);
}
});
$('.subMenu').on('mousedown','ul', function(e){
e.stopPropagation();
alert('menu item clicked');
});
})
这篇关于单击以关闭移动设备上的jQuery下拉菜单,同时保留其他行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!