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

。_饼干妹妹 提交于 2019-12-01 01:42:20

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();
});

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);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!