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
465 views
in Technique[技术] by (71.8m points)

jquery - Animating "src" attribute

I have an HTML document. It looks like this:

original

When the user hovers "stackinfo" image, I want it look like this:

hovered

My code for image:

<img src="/Resources/Images/MainMenu/logo.png" name="Logo" width="100" height="30" class="MainMenu" id="Logo" />

I know how to change the src of the image on hover, but how can I animate this?

(I want to do it with jQuery)

What I have already tried:

$(document).ready(function(){
       $('img[name="Logo"]').hover(function(event){
         $(this).fadeIn(function(event){
             $(this).attr("src","/Resources/Images/MainMenu/logoHover.png");
         });
       },
       function(event){
         $(this).fadeToggle(function(event){
             $(this).attr("src","/Resources/Images/MainMenu/logo.png");
         });  
       });
});
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can't animate the .src value directly with jQuery.

You will need to use two images, positioned on top of one another so one can be faded in on top of the other.

Both images should be preloaded or precached so there is no delay for an image to load after setting .src.

Working example: http://jsfiddle.net/jfriend00/n52Fr/

$(".container").hover(function() {
    $(this).find(".fadeTop").fadeOut(1000);
}, function() {
    $(this).find(".fadeTop").fadeIn(1000);
});?


<div class="container">
    <img src="http://photos.smugmug.com/photos/344291068_HdnTo-Th.jpg">
    <img class="fadeTop" src="http://photos.smugmug.com/photos/344290962_h6JjS-Th.jpg">
</div>? 


.container {
    position: relative;
    height: 100px;
    width: 150px;
}

.container img {
    position: absolute;
    top: 0;
    left: 0;
}

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

...