问题
I've got an item list where I want to show a related panel if the item list item is hovered over. I've got it working but the issue is that I cannot then hover over content within the panel once I've hovered over the linked list item for obvious reasons as I use a mouseleave
function.
I've been at this for a few days and cannot work out the logic of what needs to be done to leave the related panel open so I can hover over it and click a read more link within it.
I tried adding a class on the hover state to the panel but that did not seem to work either.
My HTML is:
<div id="item-wrapper">
<ul>
<li><a href="#" id="item-1">Item 1</a>
</li>
<li><a href="#" id="item-2">Item 2</a>
</li>
</ul>
</div>
<div id="panel-1" class="panel">
<h2>This is panel 1!</h2>
<a href="#">read more 1...</a>
</div>
<div id="panel-2" class="panel">
<h2>This is panel 2!</h2>
<a href="#">read more 2...</a>
</div>
My basic jQuery is:
$('#item-1').mouseenter(function () {
$('#panel-1.panel').toggle();
});
$('#item-1').mouseleave(function () {
$('#panel-1.panel').toggle();
});
$('#item-2').mouseenter(function () {
$('#panel-2.panel').toggle();
});
$('#item-2').mouseleave(function () {
$('#panel-2.panel').toggle();
});
... and then I have some CSS where the panels are set to display: none
to begin with. Note, if neither list item links are hovered then the panels should go away if one had been open previous to that.
Fiddle demo here...
回答1:
In my opinion, the only real way to approach this is to wrap the hidden elements in the element that you are hovering, so that the mouseleave event can be tied to the wrapper.
LINK UPDATED: here's a fiddle
I also used data attributes on the elements to track which panel to open. This way, you only need the following code:
$('#item-wrapper a').mouseenter(function (e) {
if ($(this).data('panel')) {
$('.panel').hide();
$('#' + $(this).data('panel')).show();
}
});
$('#item-wrapper').mouseleave(function () {
$('.panel').hide();
});
EDIT: added a conditional to make sure anchor tags in the panels don't trigger the hover event.
回答2:
A couple things:
- User a hover event handler on the
li
, not thea
. - This allows you to move your content into the
li
s, so that hovering on the content means you're still hovering over its parent, theli
.
jQuery:
$('#item-1').parent().hover(function () {
$('#panel-1.panel').toggle();
});
$('#item-2').parent().hover(function () {
$('#panel-2.panel').toggle();
});
Forked jsFiddle
来源:https://stackoverflow.com/questions/18474972/jquery-show-hide-panel-and-then-hover-over-content-within-a-panel