How to detect mouseleave() on two elements at once?

后端 未结 5 1337
别跟我提以往
别跟我提以往 2020-12-06 11:15

Answer can be in vanilla js or jQuery. I want to hide a div with the id \"myDiv\" if the user is no longer hovering over a link with the id \"myLink\" or a span with the id

相关标签:
5条回答
  • 2020-12-06 11:56

    You could use a multiple selector:

    $("#someElement, #someOtherElement").mouseleave(function() {
       // Do something.
    });
    
    0 讨论(0)
  • 2020-12-06 12:05

    While the answer from lonesomeday is perfectly valid I changed my html to have both elements in one container. I originally wanted to avoid this hence I had to do more refactoring for my clients in other html templates, but I think it will pay out on the long term.

    <div id="my-container">
     <div class="elem1">Foo</div>
     <div class="elem2">Bar</div>
    </div>
    
    $('#my-container').mouseleave(function() { console.log("left"); });
    
    0 讨论(0)
  • 2020-12-06 12:06

    You can beautifully use setTimeout() to give the mouseleave() function some "tolerance", that means if you leave the divs but re-enter one of them within a given period of time, it does not trigger the hide() function.

    Here is the code (added to lonesomeday's answer):

    var count = 0;
    var tolerance = 500;
    $('#d1, #d2').mouseenter(function(){
        count++;
        $('#d3').show();
    }).mouseleave(function(){
        count--;
        setTimeout(function () {
            if (!count) {
                $('#d3').hide();
            }
        }, tolerance);
    });
    

    http://jsfiddle.net/pFTfm/195/

    0 讨论(0)
  • 2020-12-06 12:18

    Something like this should work:

    var count = 0;
    $('#myLink, #mySpan').mouseenter(function(){
        count++;
        $('#myDiv').show();
    }).mouseleave(function(){
        count--;
        if (!count) {
            $('#myDiv').hide();
        }
    });
    

    jsfiddle

    0 讨论(0)
  • 2020-12-06 12:18

    I think, it's your solution!!!

    $(document).ready(function() {
        var someOtherElement = "";
        $("#someElement").hover(function(){
            var someOtherElement = $(this).attr("href");
            $(someOtherElement).show();
        });
        $("#someElement").mouseleave(function(){
            var someOtherElement= $(this).attr("href");
            $(someOtherElement).mouseenter(function(){
            $(someOtherElement).show();
            });
            $(someOtherElement).mouseleave(function(){
            $(someOtherElement).hide();
            });
    
        });
    });
    
    ----
    html
    ----
    <div id="someElement">
                    <ul>
                      <li><a href="#tab1">element1</a></li>
                      <li><a href="#tab2">element2</a></li>
            </ul>       
    </div>
    
    <div id="tab1" style="display: none"> TAB1 </div>
    <div id="tab2" style="display: none"> TAB1 </div>
    
    0 讨论(0)
提交回复
热议问题