2010-03-09 121 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來做到這一點,但無論在哪種情況下,您都需要將圖像完全置於彼此之上。