jQuery show / hide panel and then hover over content within a panel

跟風遠走 提交于 2019-12-11 19:33:46

问题


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:

  1. User a hover event handler on the li, not the a.
  2. This allows you to move your content into the lis, so that hovering on the content means you're still hovering over its parent, the li.

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

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