Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...