Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
912 views
in Technique[技术] by (71.8m points)

jquery - fadeOut/fadeIn background image on hover

I have a <div> which contains a background image, the <div> sits within a toolbar in 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;
}

When the mouse hovers over #toolbar I want the background image of .image to change but using .fadeOut() and .fadeIn()

So far I have:

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

Currently the logo fades out and the hover logo fades in twice.

Any help appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's no way to do smooth transitions between images in jQuery - it doesn't know how to translate between one image and the next. You can do colour transitions with a plugin.

You can do some of this with CSS transitions. You can only use transitions on values set in CSS and they're not in all the browsers yet:

/* 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 */
}

This will have a pretty fade effect on mouseover, the change in opacity will still happen in IE, but without the fade transition.

Another option is to fade the images in and out on top of one another - you could do this with jQuery hover events or CSS, but in either case you'll need the images to be absolutely positioned on top of one another.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...