简体   繁体   中英

How can I prevent a jquery animation from firing when a selectbox is active

The following jsfiddle demonstrates the problem. In Firefox, hover over 'highlight stories' and try to select from the second drop-down: the containing ul animates closed and it is impossible to select an option. It is also possible to get into a flickering loop by selecting from the top select box and moving the mouse down slightly.

I can remove the mouseleave event by doing something like this:

$('.selector').click(function(){
      $('nav ul li').unbind('mouseleave');
});

But this obviously prevents the hover animation from firing correctly. Can anyone suggest a more elegant solution?

http://jsfiddle.net/codecowboy/mDUa9/8/

Here's my attempt: http://jsfiddle.net/rPe9r/

$('nav ul li').hover(function() { // mouse enter
    $('ul', this).slideDown(100);
    }, function() { // mouseout
        var container = $("ul", this);
        // Hide popup if dropdown menu is not active
        if (!container.hasClass("dropdown-active")) {
            container.slideUp(100);
        }
    });

$("nav select").bind("focus", function() {
    $(this).closest("ul").addClass("dropdown-active");
}).bind("change focusout", function() {
    $(this).closest("ul").removeClass("dropdown-active");
});

The code tries to determine when a select box is active and supresses the slideUp of the container on mouseleave when any of the select boxes are active.

I've only tested this in Firefox, and I suspect this may be too simplistic and may not cover all uses cases (for instance, when user selects an already selected item from the dropdown which will not trigger the change event). Further testing/tweaking may be required.


Perhaps a more robust method would be to dynamically scale the height of the container when the dropdown box expands such that the mouse does not leave the container when users navigate the dropdown menu. Of course, the difficulty here is to determine the size of a select dropdown menu in a portable way.

A possible workaround would be to use one of the many jquery plugins available out there that replaces <select> with a <div> . This gives you more flexibility in styling your dropdown menus, and more importantly, allow you to tweak your css such that the containing div is scaled automatically when the dropdown menu is expanded.

Just a thought.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM