Funky jQuery mouseleave behavior

后端 未结 5 879
别跟我提以往
别跟我提以往 2021-02-04 19:32

I have a menu-like drop down container that hides via binding the \"mouseleave\" event.

提交评论

  • 2021-02-04 19:47

    An update on Blocka's solution as it doesn't work with Firefox correctly:

    if ((typeof e.fromElement != 'undefined' && !e.fromElement.length) ||
        (typeof e.fromElement == 'undefined' && e.target.tagName != 'SELECT')) {
        // perform your mouseleave logic
    }
    
    0 讨论(0)
  • 2021-02-04 19:57

    Perhaps when the dropdown is expanded you could set a flag. Clear the flag when an item is selected. When a mouseleave occurs, don't hide the menu unless the flag is clear.

    I always get nervous about hacking UI events to this degree though, since it's likely you'll end up leaving some browser somewhere in a totally unusable state.

    0 讨论(0)
  • 2021-02-04 19:57

    Most renderers (all except Gecko, I think) implement opened <select> menus and their options in a separate "window", not as elements on the page. The page is, then, not necessarily aware of the user's interaction with an open <select> menu. It's very unlikely that you'll be able to achieve the desired effect across all the major browsers...

    Edit: ... but maybe so. This works for me in Safari and Firefox. I can't test in IE right now, but give it a shot:

    var timer;
    $('#container').mouseleave(function(e) {
        if($(e.target).parents('#container').length) {
            return;
        }
        timer = setTimeout(function() {
            $('#container select').blur();
        }, 50);
    }).mouseenter(function(e) {
        if(timer) {
            clearTimeout(timer);
        }
    });
    

    Edit 2: actually, Safari doesn't fire mouseleave (or mouseout) at all when the <select> "window" is open.

    0 讨论(0)
  • 2021-02-04 20:00

    A very simple and effective solution to this is to control the mouse pointer coordinates before performing the action. If the container out of focus to focus on the element "select", it checks the pointer. If the pointer is inside the container, it does not perform any action, however if this is the container element action is performed

     $('#div_solapa_lateral').bind("mouseenter",function(){
                $(this).animate({left:'0'},500);
            });
    
        $('#div_solapa_lateral').bind("mouseleave",function(e){
                if ( e.clientX>360 || e.clientY<60 || e.pageY>625 )
                $(this).animate({left:'-320'},500);
            });
    

    clientX and clientY to "position:relative;" pageX and pageY to "position:absolute;"

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