jQuery on('hover') Event Replacement

后端 未结 3 1638
难免孤独
难免孤独 2021-01-22 07:35

I\'m looking to swap an img src on hover. Typically I would use:

$(\'#img\').hover(function() {
    $(this).attr(\'src\', \'http://www.example.com/new-img.jpg\'         


        
相关标签:
3条回答
  • 2021-01-22 07:49

    No, you'll need to do it in two calls. But for added jQuery points, you can chain them:

    $('#main').on('mouseenter', '#img', function() {
       $('#img').attr('src', 'http://www.example.com/new-img.jpg');
    }).on('mouseleave', '#img', function() {
       $('#img').attr('src', 'http://www.example.com/old-img.jpg');
    });
    

    And as Benjamin comments below, you can optimise further (you get plain old Javascript points this time):

    $('#main').on('mouseenter', '#img', function() {
       this.src = 'http://www.example.com/new-img.jpg';
    }).on('mouseleave', '#img', function() {
       this.src = 'http://www.example.com/old-img.jpg';
    });
    
    0 讨论(0)
  • 2021-01-22 07:59

    You can apply multiple events and then check event.type like this:

    $('#main').on('mouseenter mouseleave', '#img', function(e) {
        $(this).attr('src', 'http://www.example.com/' + (e.type == 'moseenter' ? 'new-img.jpg' : 'old-img.jpg'));
    });
    

    jsFiddle

    You can also use switch-case or if/else:

    $('#main').on('mouseenter mouseleave', '#img', function(e) {
        switch(e.type) {
            case 'mouseenter':
                $(this).attr('src', 'http://www.example.com/new-img.jpg');
                break;
            case 'mouseleave':
                $(this).attr('src', 'http://www.example.com/old-img.jpg');
                break;
        }
    }
    
    0 讨论(0)
  • 2021-01-22 08:12

    Here is an alternative approach that involves no JavaScript at all:

    Instead of using an <img> with a src attribute use a div, give that div the same id (remember to give it the right width and height).

    In your css, give that div a background-image something like:

    #img{ 
        background-image: url('http://www.example.com/old-img.jpg');
    }
    

    On :hover change it

    #img:hover{ 
        background-image: url('http://www.example.com/new-img.jpg');
    }
    

    (fiddle)

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