Problem with jQuery mouseleave firing when container has select box

后端 未结 9 2227
一整个雨季
一整个雨季 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-13 23:58

    I had the same problem in a project in which I am contributing, and the other answers didn't work fine for me. My tricky solution was to check if the mouse position inside the event object is inside the parent container. Works pretty good!

    var layer = $('#parent-container'),
        layerPos = {};
    $(layer).mouseenter(function () {
        var $this = $(this),
        $selectOptionsContainer = $this.find('#child-container');
        $selectOptionsContainer.stop().fadeTo('slow', 1.0, function(){
            layerPos.x = {
                min: $(layer).offset().left,
                max: $(layer).offset().left + $(layer).width()
            };
            layerPos.y = {
                min: $(layer).offset().top,
                max: $(layer).offset().top + $(layer).height()
            };
        });
    })
    $(layer).mouseleave(function(e) {
        // check if event mouse position is inside parent container
        var x_con = e.pageX >= layerPos.x.min && e.pageX <= layerPos.x.max;
        var y_con = e.pageY >= layerPos.y.min && e.pageY <= layerPos.y.max;
        if ( x_con && y_con ) {
            return false;
        }
    
        var $this = $(this),
        $selectOptionsContainer = $this.find('#child-container');
        $selectOptionsContainer.stop().hide();              
    });
    

    You can also check the navigator version to avoid this code to execute in browsers that support this functionality like Chrome.

提交回复
热议问题