jQuery on('hover') Event Replacement

一个人想着一个人 提交于 2019-12-02 10:06:59

问题


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');
});

However, I'm loading the content in via Ajax so normally I would use:

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

But I'm reading that on('hover', ...) was deprecated in jQuery 1.8 and removed in 1.9 (jQuery Docs), which is what I'm currently using. Do anyone have any work arounds other than using:

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

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

回答1:


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';
});



回答2:


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;
    }
}



回答3:


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)



来源:https://stackoverflow.com/questions/17301437/jquery-onhover-event-replacement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!