jquery - foverOut / fadeIn悬停时的背景图片

时间:2010-03-09 11:57:47

标签: jquery

我有<div>,其中包含背景图片,<div>位于HTML工具栏中。

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

目前徽标淡出,悬停徽标淡出两次。

任何帮助表示感谢。

3 个答案:

答案 0 :(得分: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来做到这一点,但在任何一种情况下你都需要将图像绝对放在彼此之上。

答案 1 :(得分: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   
});

答案 2 :(得分:1)

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

所以它会是这样的:

$("#toolbar img:hover").switchClass("image","imagehover", "slow");
相关问题