How can I show a div only when hovering a menu item or the div?

后端 未结 2 1293
小鲜肉
小鲜肉 2021-01-07 15:10

I have items contained in an unordered list. I have hidden divs (using display:none;) outside of this list. When you hover over a list item, I would like the div to appear

相关标签:
2条回答
  • 2021-01-07 15:42

    Something like this should work.

    Using .hover to bind the event, .index and .eq to find which one to show/hide and the native JS methods for timeouts to let you hover the divs.

    var timeout; // store a timeout here
    
    $('#main-menu lia ').hover(function ()
    {
        $('.widget-container').eq($(this).parent().index()).show();
    }, function ()
    {
        timeout = setTimeout(function ()
        {
            $('.widget-container').eq($(this).parent().index()).hide();
        }, 1000);
    );
    
    $('.widget-container').hover(function ()
    {
        clearTimeout(timeout);
    }, function ()
    {
        timeout = setTimeout(function ()
        {
            $(this).hide();
        }, 1000);
    });
    
    0 讨论(0)
  • 2021-01-07 15:55

    You can wrap the widgets in a div and attach a mouseleave event to it. This solution also uses the rel attibute to store the widget id: DEMO

    HTML

    <div id="wrap">
        <nav id="main-menu">
            <ul>
                <li><a class="first-link parent" rel="first-widget" href="">First Link</a></li>
                <li><a class="second-link parent" rel="second-widget" href="">Second Link</a></li>
                <li><a class="third-link parent" rel="third-widget" href="">Third Link</a></li>
                <li><a class="fourth-link parent" rel="fourth-widget" href="">Fourth Link</a></li>
            </ul>
        </nav><!-- #main-menu !-->
    
        <div id="first-widget" class="widget-container">
                    <h2>Sub Title 1</h2>              
                    <p>Lorem Ipsum
                    <a href="#">Read More</a></p>
         </div><!-- .first-widget !-->
          ...
    </div>
    

    JS

    $('#main-menu a').mouseover(function() {
       var $this = $(this);
       var id = $this.attr('rel');
       var $currentWidget = $('#' + id);
       $currentWidget.show().siblings('.widget-container').hide();
    });
    $('#wrap').mouseleave(function() {
        $('.widget-container').hide();
    });
    
    0 讨论(0)
提交回复
热议问题