2010-03-09 119 views
8

我有一个<div>其中包含背景图像,<div>位于HTML中的工具栏内。jquery - 淡入淡出在悬停的背景图像

HTML:

<div id="toolbar"> 
    <div class="image">&nbsp;</div> 
</div> 

CSS:

#toolbar .image { 
background url('images/logo.png') no-repeat top left; 
} 

#toolbar .imagehover { 
background url('images/logoHover.png') no-repeat top left; 
} 

当鼠标悬停在#toolbar我想要的.image背景图像改变,但使用.fadeOut().fadeIn()

到目前为止,我有:

$("#toolbar").hover(function() { 
    $(".image").fadeOut("slow"); 
    $(".image").addClass("imagehover"); 
    $(".imagehover").fadeIn("slow"); 
    }, 
    function() { 
    $(this).removeClass("imagehover"); 
}); 

当前标志淡出,悬停标志两次消失。

任何帮助表示赞赏。

+0

您无法更改背景元素的不透明度,这是fadeIn()的作用 - 您可能需要隐藏元素并将其完全放置,然后淡入淡出。 – 2010-03-09 12:00:50

回答

4
//Use the fad in out callback 
$("#toolbar").hover(function() { 
    $(".image").fadeOut("slow", function() { 
     $(this).addClass("imagehover").fadeIn("slow", function() { 
      $(this).removeClass("imagehover"); 
     }); 
    }); 

}); 

//or you can use animate 
$("#toolbar").animate({ 
    "class": "imagehover" 
}, "slow", 'easein', function() { 
    //do what every you want 
}); 
+0

removeClass部分应该作为悬停出来的回调,而不是回调到新类的fadeIn ...可能是一个混乱的括号的情况:) ... – 2010-03-09 12:10:00

1

由于您无法淡化背景图像,因此您可以尝试switchClass(),您可以将其设置为计时器。我不确定你会得到一个纯粹的淡出和淡入,但你可能会得到一个很酷的变形效果。

因此,这将是这样的:

$("#toolbar img:hover").switchClass("image","imagehover", "slow"); 
+0

什么是switchClass()? – tetris 2012-03-17 20:13:52

+0

我相信它是jQuery UI的扩展函数 - http://jqueryui.com/ – 2012-09-14 14:20:12

+0

它在jQuery UI Core中http://docs.jquery.com/UI/Effects/switchClass – Aaron 2012-12-10 18:05:08

6

有没有办法做到的图像之间的平滑过渡jQuery的 - 它不知道如何将一张图像和下之间的转换。你可以用插件做颜色转换。

你可以用CSS转换做一些这样的事情。您只可以在CSS中设置的值使用的过渡,他们还没有在所有的浏览器尚未:

/* faded out logo class */ 
.faded-logo { 
    opacity: 0.30;     /* FX, Safari, GC, Opera, decent browsers */ 
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=30)"; /* IE8 */ 
    filter: alpha(opacity=30);           /* IE */ 

    background: url('images/logo.png') no-repeat top left; 

    /* in Safari, FX and Chrome add a fade transition */ 
    -webkit-transition: opacity .25s linear .1s; 
    transition: opacity .25s linear .1s; 
} 

/* no opacity on hover */ 
.faded-logo:hover { 
    opacity: 1;      /* FX, Safari, GC, Opera, decent browsers */ 
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; /* IE8 */ 
    filter: alpha(opacity=100);           /* IE */ 
} 

这将对鼠标悬停一个漂亮的淡入淡出效果,不透明度的变化仍然会发生在IE浏览器,但没有淡入淡出的过渡。

另一种选择是淡入淡出图像 - 您可以使用jQuery悬停事件或CSS来做到这一点,但无论在哪种情况下,您都需要将图像完全置于彼此之上。