问题描述:

I have a simple CSS-driven dropdown menu. I'm using jQuery to toggle the dropdown via 'click' or 'hover.' However, if clicking "Menu" twice (to show, then hide again), the hover state becomes disabled. In this scenario, does anyone know a way to return a toggle using a hover state?

JSFiddle

Many thanks!

HTML

<ul class="menu">

<li> <a class="trigger">MENU</a>

<ul class="dropdown">

<li><a href="#">Item 1</a></li>

<li><a href="#">Item 2</a></li>

<li><a href="#">Item 3</a></li>

<li><a href="#">Item 4</a></li>

<li><a href="#">Item 5</a></li>

</ul>

</li>

</ul>

CSS

.menu, .menu ul {

list-style:none;

cursor:pointer;

margin:0;

padding:0;

}

.menu a {

float:left;

text-decoration:none;

color:#000;

}

.menu li:hover > a {

color:#666;

}

.menu ul {

opacity:0;

visibility:hidden;

position:absolute;

top:25px;

z-index:1;

background:#666;

}

.menu li:hover > ul {

opacity:1;

visibility:visible;

}

.menu ul a {

padding:5px;

display:block;

text-transform:none;

}

.menu ul a:hover {

background-color:lightgray;

}

jQuery

$('.trigger').on("click hover", function() {

$('.dropdown').toggle();

});

网友答案:

It's not here, but i'm sure you have into your CSS this line of code:

.trigger:hover .dropdown {
   display: block;
}

I recommend you to add this into your CSS.

.trigger:hover .dropdown,
.trigger.clicked .dropdown {
   display: block;
}

This shows the menu when you hover this <li> and when it has clicked class.

Then, you have to add this line of javascript:

var timeoutMenu = null;
$('.trigger').on("click", function() {
    $('.dropdown').toggleClass('active');
});

$('.trigger').hover(function() {
    clearTimeout(timeoutMenu);
    $('.dropdown').toggleClass('active');
}, function() {
    setTimeout(function() {
      $('.dropdown').removeClass('active');
    }, 500);
});

When you hover the menu, its submenu appears, and when you mouseout it, the menu hides in 500ms.

Hope it helps.

Regards.

相关阅读:
Top