How to stop toggle event from being fired multiple times on mouseenter/mouseleave?

前端 未结 3 1606
说谎
说谎 2021-01-01 03:51

I\'m using jQuery to toggle the visibility of a

using the jQuery toggle method. The toggle is fired on the mouseenter and mouseleave event, thus cre
相关标签:
3条回答
  • 2021-01-01 04:16

    Two things:

    1. If you're going to use both mouseenter and mouseleave I'd suggest using the hover() function; and

    2. When using triggered animations it's a good habit to get into to use the stop() method.

    So:

    $("div.someclass").hover(function() {
      $("...").stop().fadeIn("slow");
    }, function() {
      $("...").stop().fadeOut("slow");
    });
    

    Note: replace "..." with the appropriate selector for what you're toggling and use the appropriate effect (I'm using fade here). Also, this in an event handler refers to the source of the event.

    0 讨论(0)
  • 2021-01-01 04:16

    Aside from the correct answer by Cletus, i'd like to point out that using mouseenter and mouseleave events is not wrong. The trick only resides into the stop() method, in fact we could still do:

    $("div.someclass").on("mouseenter", function() {
      $("...").stop().fadeIn("slow");
    });
    $("div.someclass").on("mouseleave", function() {
      $("...").stop().fadeOut("slow");
    });    
    

    Here is a jsFiddle example :)

    0 讨论(0)
  • 2021-01-01 04:35

    You can use the more common mouseover/mouseout events to get a hover event that doesn't fire on internal mouse movements.

    But don't use toggle on a mouse event, it can easily go wrong if eg. the mouse is over the element at page load time, or the mouse leaves the browser (which can allow the mouse to leave the bounds of the element without firing a mouseout). Have separate function for over which shows the content, and out which hides it.

    Better: just use the hover() method which is meant for exactly this purpose.

    0 讨论(0)
提交回复
热议问题