将鼠标悬停在同级元素上的 jquery 上轻拂

mouseover jquery on sibling elements flick

本文关键字:jquery 元素 鼠标 悬停      更新时间:2023-09-26
$('body').on({
    mouseenter: function () {
        $(this).siblings('span').show();
    },
    mouseleave: function () {
        $(this).siblings('span').show().hide();
    }
}, "div");

我像这样放置我的 html

<div></div>
<span>x</span>

当我将鼠标悬停在跨度上时它会闪烁,如何在不将跨度作为孩子移动到 DOM 中的框中的情况下解决这个问题?

这是因为您没有正确附加事件:

$('body div').hover(function(){//mouseover event
  $(this).next().show();
},function(){//mouseleave event
  $(this).next().hide();
});

您还可以缩小代码范围以在悬停时使用.toggle()

$('body').on('hover','div',function(){
  $(this).next().toggle();
});

由于要将事件绑定到span:

$('body').on("hover", "span", function(){
  $(this).show();
},function(){
  $(this).hide();
});

您甚至可以使用mouseenter和mouseleave:

 $('body').on("mouseenter","span", function(){
      $(this).show();
    }).on("mouseleave", "span",function(){
      $(this).hide();
    });