jQuery 将鼠标悬停在子元素上会产生奇怪的效果

发布于 2024-08-07 07:57:25 字数 618 浏览 3 评论 0原文

我有这个标记(简化的):

<div class='item'>
  <a> one link </a>
  <a class='trash'><img src='trash.png'/></a>
</div>

当鼠标进入时,我突出显示 div,并显示(否则隐藏的)“垃圾”链接(它就像一个小垃圾箱),以便用户可以删除该链接。

我无法使用“悬停”效果,因为我需要它们是实时事件。所以我正在做鼠标悬停和鼠标移出。这是代码:(

$('div.link').live('mouseout', function(e){
        console.log(e)
        if(e.target == this){
            $(this).removeClass('hover');
            $(this).children('a.trash').fadeOut();
        }
    });

鼠标悬停则执行完全相反的操作)。

虽然动画看起来很奇怪,我做错了什么?

非常感谢!

I've got this markup (simplified):

<div class='item'>
  <a> one link </a>
  <a class='trash'><img src='trash.png'/></a>
</div>

I'm highlighting the div when the mouse enters, and showing the (otherwise hidden) 'trash' link (it's like a tiny trash bin) so the user can delete the link.

I can't use 'hover' effect, because I need them to be live events. So I'm doing mouseover and mouseout. This is the code:

$('div.link').live('mouseout', function(e){
        console.log(e)
        if(e.target == this){
            $(this).removeClass('hover');
            $(this).children('a.trash').fadeOut();
        }
    });

(mouse over does the exacto opposite).

The animation looks quirky though, what am I doing wrong?

Thanks so much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹏半生如梦愿梦如真 2024-08-14 07:57:25

当鼠标进入和离开任何子元素时,也会触发 mouseovermouseout 事件。尝试改用 mouseentermouseleave 事件。

不幸的是, live 方法当前不支持这些方法。添加/删除链接时,您必须手动绑定它们。

function toggleDelete() {
      $(this)[($(this).hasClass('hover') ? 'remove' : 'add') + 'Class']('hover');
      $(this).find('a.trash').toggle();
}

$('div.link').bind('mouseenter, mouseleave', toggleDelete);

$('.add').click(function(e) {
    var link = $('<a />').addClass('link');
    link.bind('mouseenter, mouseleave', toggleDelete);
    $('.parent').append(link);
});

The mouseover and mouseout events are also fired when the mouse enters and leaves any child elements. Try using the mouseenter and mouseleave events instead.

Unfortunately, the live method doesn't currently support these methods. You'll have to bind them manually when you add/remove links.

function toggleDelete() {
      $(this)[($(this).hasClass('hover') ? 'remove' : 'add') + 'Class']('hover');
      $(this).find('a.trash').toggle();
}

$('div.link').bind('mouseenter, mouseleave', toggleDelete);

$('.add').click(function(e) {
    var link = $('<a />').addClass('link');
    link.bind('mouseenter, mouseleave', toggleDelete);
    $('.parent').append(link);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文