Problem with jQuery mouseleave firing when container has select box

后端 未结 9 2196
一整个雨季
一整个雨季 2021-02-13 23:47

I have a two containers -- one is nested inside of another. When I hover over the parent, I want the child container to appear. When I mouseout, I want the child container to f

相关标签:
9条回答
  • 2021-02-14 00:07

    You should only check if the current Element is a descendant of your container.

    If so abort the handler.

    See: jquery descendant

    Example:

    ContainerElement.mouseleave(function (e) {
    if (ContainerElement.has(e.fromElement).length > 0) return;
    // Do your Stuff
    });
    
    0 讨论(0)
  • 2021-02-14 00:14

    This partly solves the problem. Unbind the mouseleave event when the select box gains focus and bind again when it loses focus.

    http://jsfiddle.net/9TZyh/5/

    $('#parent-container').live("mouseenter", function() {
        var $this = $(this);
        $selectOptionsContainer = $this.find('#child-container');
        $selectOptionsContainer.stop().fadeTo('slow', 1.0);
    }).live("mouseleave",focusOut);
    $("#select-grind-type").live("focus",function(){
        $('#parent-container').die("mouseleave");
    });
    $("#select-grind-type").live("focusout change",function(){
        $('#parent-container').live("mouseleave",focusOut);
    });
    function focusOut(e) {
        var $this = $(this),
            $selectOptionsContainer = $this.find('#child-container');
        $selectOptionsContainer.stop().hide();
    }
    
    0 讨论(0)
  • 2021-02-14 00:14

    So I just ran into a similar issue with a <select> nested in a container and came across this question. Here's what I ended up doing.

                   $("#container").mouseover(function(e){
                                var t = $(this);
                                t.addClass('active');
                                var offset = t.offset();
                                var xMin = offset.left;
                                var yMin = offset.top;
                                var xMax = xMin + t.innerWidth();
                                var yMax = yMin + t.innerHeight();
    
                                t.parent().mousemove(function(e){
                                        if(e.pageX < xMin || e.pageX > xMax-2 || e.pageY < yMin || e.pageY > yMax ){
                                                t.removeClass('active');
                                                // unbind this event
                                                $(this).unbind('mousemove');
                                        }
    
                                });
                        });
    

    Basically, when you mouseover the container, we collect its bounds and start checking whether or not the mouse is over the element. When we know the mouse is gone, we unbind the mousemove listener.

    I'd make a jsfiddle for you but its running so slow today!

    Hope that helps.

    0 讨论(0)
提交回复
热议问题