0

Unfortunately I am having issues with the disappearing of the drop down. I'm currently using toggleClass to add/remove the class on click but I also need this process undone when the menu is blurred ie: clicking anywhere else on the page etc. Here is my jquery code:

$(function() {$('#srt-btn').click(function() {$('ul.toggle-off').toggleClass('toggle-on')});});

<ul id="sort">
<li><a id="srt-btn" class="srt-title">Sort ▾&lt;/a>
        <ul class="sort-menu toggle-off">
            <div class="droid"></div>
            <li class="top"><a href="#">Notes</a></li>
            <li><a href="#">Photos</a></li>
            <li><a href="#">Videos</a></li>
            <li class="divider"></li>
            <li class="btm"><a href="#">Make List</a></li>
    </ul>
    </li>

4

3 回答 3

1

您还可以使用 stopPropagation 取消点击事件

$(function() {
    $('#srt-btn').click(
        function(e) {
            $('ul.sort-menu').slideToggle();
            e.stopPropagation();
        }
    );
    $('.sort-menu li').click(
        function(e) {
            $('ul.sort-menu').slideUp();
            e.stopPropagation();
        }
    );
    $(document).click(
        function(){
            $('ul.sort-menu').slideUp();
        }
    );

});

并且不要忘记将您的菜单选项 ul 设置为 position:absolute 否则您的元素会移动

这是一个jsFiddle

于 2012-09-11T21:08:10.747 回答
1
function toggleMenu() 
{   
     $('ul.toggle-off').toggleClass('toggle-on');
}


$(function() {
     $('#srt-btn').click(toggleMenu);
     $('#srt-btn').blur(toggleMenu);
});

工作示例。

于 2012-09-11T20:37:35.920 回答
0

你可以尝试这样的事情:

var IsInside = false,
    $sortMenu = $('#sort'),
    $toggleOn = $('.toggle-off');

$sortMenu.on('mouseenter', '#srt-btn', function(){
  IsInside = true;
}).on('mouseleave', '#srt-btn', function(){
  IsInside = false;
});

$sortMenu.on('click', '#srt-btn', function(){
  $toggleOn.toggleClass('toggle-on');
});

$(document).on('click', 'body', function(){
  if(!IsInside) {
    $toggleOn.removeClass('toggle-on');
  }
});

这里有一个jsFiddle

于 2012-09-11T21:05:36.643 回答