jQuery显示/隐藏面板,然后将鼠标悬停在面板中的内容上 [英] jQuery show / hide panel and then hover over content within a panel

查看:103
本文介绍了jQuery显示/隐藏面板,然后将鼠标悬停在面板中的内容上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表,如果该项目列表项悬停在这里,我想在其中显示相关面板.我已经可以使用它了,但问题是,由于明显的原因,当我使用mouseleave函数时,一旦将鼠标悬停在链接列表项上,便无法将鼠标悬停在面板上的内容上.

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.

我的HTML是:

<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>

我的基本jQuery是:

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

...然后我有一些CSS,面板首先设置为display: none.请注意,如果两个列表项链接都没有被悬停,则如果之前已打开一个面板,则面板应该消失.

... 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.

此处显示小提琴演示...

推荐答案

在我看来,解决此问题的唯一真实方法是将隐藏的元素包装在要悬停的元素中,以便可以绑定mouseleave事件到包装纸.

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.

链接已更新: 这是一个小提琴

我还使用了元素上的数据属性来跟踪要打开哪个面板. 这样,您只需要以下代码:

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

添加了一个条件,以确保面板中的锚标签不会触发悬停事件.

added a conditional to make sure anchor tags in the panels don't trigger the hover event.

这篇关于jQuery显示/隐藏面板,然后将鼠标悬停在面板中的内容上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆