using on() with hover - jQuery

后端 未结 7 1205
感情败类
感情败类 2021-01-26 05:51

This is what I have:

$(\'#blah\').hover(function(){
    $(\'etc\').show();
}, function(){
    $(\'etc\').hide();
});

This works just fine, now

相关标签:
7条回答
  • 2021-01-26 05:56

    use

     jQuery.on("hover","#blah", function..)
    

    Or you can use toggle feature of jQuery too

    0 讨论(0)
  • 2021-01-26 06:01

    Use mouseenter and mouseleave for hover. Check using hover with on here.

    $("#blah").on(
    {
        mouseenter: function() 
        {
            //stuff to do on mouseover
        },
        mouseleave: function()
        {
            //stuff to do on mouseleave
        }
    });
    

    Use toggle to show / hide,

    $('#blah').on('hover', function(){
        $('#etc').toggle();
    });
    
    0 讨论(0)
  • 2021-01-26 06:05

    From the JQuery source code, hover is not included in the event list that triggered leading to JQuery .on()

    jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
        "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
        "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
    
        // Handle event binding
        jQuery.fn[ name ] = function( data, fn ) {
            return arguments.length > 0 ?
                this.on( name, null, data, fn ) :
                this.trigger( name );
        };
    });
    

    It is because .hover() is just a shortcut for JQuery .mouseenter() and .mouseleave()

    jQuery.fn.hover = function( fnOver, fnOut ) {
        return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
    };
    

    I hope this brief explanation provides little guidance.

    0 讨论(0)
  • 2021-01-26 06:06

    Use toggle()

    $('#blah').on('hover', function(){
       $('#etc').toggle();
    });
    
    0 讨论(0)
  • 2021-01-26 06:08

    Yes it will not work because when you use .on() with hover then hover event just have one call-back function instead you can use multiple events in .on()

    Try

    $("DOM").on({
        mouseenter: function() {
            // Handle mouseenter...
        },
        mouseleave: function() {
            // Handle mouseleave...
        }
    });
    
    0 讨论(0)
  • 2021-01-26 06:15

    from Jquery docs. Jquery on

    Deprecated as of jQuery 1.8: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

    $("div.test").on({
      mouseenter: function(){
        $(this).addClass("inside");
      },
      mouseleave: function(){
        $(this).removeClass("inside");
      }
    });
    
    0 讨论(0)
提交回复
热议问题