jquery .hover 在鼠标悬停时反向加载

jquery .hover loads in reverse when mouseover

我正在使用一个简单的 jQuery 函数

$( 'foo' ).hover( function () {
     $( this ).children( 'bar' ).delay( 250 ).stop( true, true ).slideToggle( 200 );
})

我注意到,如果我将鼠标悬停在 'foo' 元素上加载页面,则悬停会反向触发。我在鼠标离开时显示并在鼠标悬停时隐藏。

有什么好的解决办法吗?

jQuery .hover 实际上是两个事件合二为一:mouseentermouseleave。您有两种使用方法,可以为每个事件指定一个函数,也可以定义一个将在两个事件上触发的函数。这就是您在那里所做的,因此您的函数将在 mouseentermouseleave 上触发。

https://api.jquery.com/hover/

如果你想让它只在mouseenter上触发,你需要按照这个结构设置它:.hover( handlerIn, handlerOut )。像这样:

    $( 'foo' ).hover( function () {
         function(){
          //this will be triggered only on mouseenter
           $( this ).children( 'bar' ).delay( 250 ).stop( true, true ).slideToggle( 200 );
         },
         function(){
         //insert here the behavior you want on mouseleave, if any
         }
    })

如果您不需要 mouseleave 上的任何行为,您只需将 .hover 更改为 .mouseenter。像这样:

$( 'foo' ).mouseenter( function () {
     $( this ).children( 'bar' ).delay( 250 ).stop( true, true ).slideToggle( 200 );
})