2

我希望在悬停时交换一个 img src。通常我会使用:

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

但是,我通过 Ajax 加载内容,所以通常我会使用:

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

但我正在阅读 on('hover', ...) 在 jQuery 1.8 中已弃用并在 1.9 (jQuery Docs)中删除,这是我目前使用的。除了使用:

$('#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');
});
4

3 回答 3

7

不,您需要在两次通话中完成。但是对于添加的 jQuery 点,您可以将它们链接起来:

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

正如本杰明在下面评论的那样,您可以进一步优化(这次您将获得普通的旧 Javascript 点):

$('#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';
});
于 2013-06-25T15:33:11.430 回答
7

您可以应用多个事件,然后event.type像这样检查:

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

jsFiddle

您还可以使用switch-caseif/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;
    }
}
于 2013-06-25T15:33:58.223 回答
1

这是一种完全不涉及 JavaScript 的替代方法:

不要使用<img>带有src属性的 div,而是为该 div 赋予相同的 id(记住给它正确的宽度和高度)。

在你的CSS中,给它div一个类似的background-image东西:

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

:hover 改变它

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

小提琴

于 2013-06-25T15:35:06.210 回答