jQuery on('hover') Event Replacement

后端 未结 3 1637
难免孤独
难免孤独 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: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;
        }
    }
    

提交回复
热议问题