0

我有以下代码:

$('.active-bean-bag ul li').hover(function() { 
    var activeBeanBag = 'menu-' + $(this).attr("class");
    $('.active-bean-bag img.menu-image').fadeOut();
    $('.active-bean-bag img.menu-image').fadeIn(function(){
            $('.active-bean-bag img.menu-image').attr("src", '/images/'+activeBeanBag+'.png');
    });
});

但是,当我将鼠标悬停在不同的LI位置上时,它看起来像是在旧图像上淡出两次,然后淡入淡出,然后淡出增益然后淡入新图像?任何想法为什么?

更新:

$('.active-bean-bag ul li').mouseover(function() { 
    var activeBeanBag = 'menu-' + $(this).attr("class");
    var newImage = '/skins/temaplate/customer/images/'+activeBeanBag+'.png';
    var $img = $('.active-bean-bag img.menu-image');
    if ($img.attr('src') != newImage) {
        $img.fadeOut(function() {
            $(this).attr("src", newImage).fadeIn();
        });
    }
});​

也尝试了相同的结果:

$(".active-bean-bag ul li").hover(function(e) {
    e.preventDefault();
        var activeBeanBag = 'menu-' + $(this).attr("class");
    $('.active-bean-bag img.menu-image').fadeOut(400, function() {
                $('.active-bean-bag img.menu-image').attr('src','/skins/template/customer/images/'+activeBeanBag+'.png');
        }).fadeIn(400);
});
4

2 回答 2

1

试试这个:

$('.active-bean-bag ul li').mouseover(function() { 
    var activeBeanBag = 'basn0g' + $(this).attr("class");
    var newImage = 'http://www.schaik.com/pngsuite/'+activeBeanBag+'.png';
    var $img = $('.active-bean-bag img.menu-image');
    if ($img.attr('src') != newImage) {
        $img.fadeOut(function() {
            $(this).attr("src", newImage).fadeIn();
        });
    }
});​

在这里摆弄:http: //jsfiddle.net/grantman16/XPthr/4/

当您只使用一个参数悬停时,您将函数绑定到 mouseenter 和 mouseleave 事件。这就是为什么它消失了两次。请参阅此处的文档:http: //api.jquery.com/hover/

于 2012-12-28T01:25:44.090 回答
0

调用fadeIn()fadeOut()同时运行,为不透明度而战。相反,将您的fadeIn()调用链接到以下回调fadeOut()

$('.active-bean-bag ul li').hover(function() { 
var activeBeanBag = 'basn0g' + $(this).attr("class");
$('.active-bean-bag img.menu-image').fadeOut(function(){
    $('.active-bean-bag img.menu-image').attr("src", 'http://www.schaik.com/pngsuite/'+activeBeanBag+'.png');
    $('.active-bean-bag img.menu-image').fadeIn();
});

});​</p>

就像在这个 jsfiddle 中一样:http: //jsfiddle.net/XPthr/5/。(我还将src分配更改为 beforefadeIn()以便它淡入并显示新图像。

于 2012-12-28T01:39:10.440 回答