2012-06-08 39 views
3

我想使用jQuery来刷图像的效果。 当我点击一个图像时,我想要1)使帧宽度为零,2)改变为另一个图像,并且3)再次使帧宽度为100%。我使用了下面的代码,无论我做什么,图像在帧扩展回100%(1-> 3-> 2)之前都会先改变。我试过使用回调函数,但无法弄清楚。有什么建议吗?我如何依次运行两个不同的jquery函数?

$("#frame img").click(function(){ 
    $("#frame").animate({width:"0%", height:"100%"}, "slow"); //1 
    $("#frame img").attr({src:"images2.png"}); //2 
    $("#frame").animate({width:"100%", height:"100%"}, "slow"); //3 
}); 

以下是我所用的回调函数试图(和我认为这是完全错误的):(如果可能的话,如.attr()不支持回调)

$("#frame img").click(function(){ 
    $("#frame").animate(({width:"0%", height:"100%"}, "slow"), function(){ 
     $("#frame img").attr(({src:"images2.png"}), function(){ 
       $("#frame").animate({width:"100%", height:"100%"}, "slow"); 
       }); 
     )}; 
}); 
+0

或者有没有什么办法,我可以通过改变图像src属性animate()函数在jQuery中? – user1427468

+0

我加了我上面试过的东西。但我认为这是完全错误的! – user1427468

回答

1

有一对夫妇的jQuery插件,做你在找什么...如果我找到它,我会回复这个答案。现在这里是你如何做到这一点。

$("#frame img").click(function(){ 
    $("#frame").animate({width:0}, "slow", function(){ 
     $("#frame img").attr({src:"images2.png"}).ready(function(){ 
      $("#frame").animate({width:$("#frame img").width()}, "slow"); 
     }); 
    }); 
}); 

.ready确保图像在重新生成之前被加载。

+0

这个作品完美!非常感谢!!! – user1427468

+1

就像@Tadeck提到的,这个代码可以通过将帧和帧的图像缓存在一个变量中进行优化。 – iDev247

2

使用回调:

$("#frame img").click(function(){ 
    $("#frame").animate({width:"0%", height:"100%"}, "slow", function(){ 
     // a callback executed, when the first animation completes 
     $("#frame img").attr({src:"images2.png"}); 
     $("#frame").animate({width:"100%", height:"100%"}, "slow"); 
    }); 
}); 

但是您的代码可以优化。的方法之一可能是这样的:

var frame = $("#frame"); // cache frame 
var images = frame.find("img"); // cache images within frame 
images.click(function(){ 
    frame.animate({width:"0%", height:"100%"}, "slow", function(){ 
     // a callback executed, when the first animation completes 
     images.attr({src:"images2.png"}); 
     frame.animate({width:"100%", height:"100%"}, "slow"); 
    }); 
}); 

(当然,除非$("#frame")$("#frame img")结果不随时间变化的)

+0

感谢您的解释!它工作完美! – user1427468

+0

@ user1427468:我很高兴我帮助:) – Tadeck

0

尝试下面的例子,并告诉我,如果这对你OK:

$('#clickme').click(function() { 
    $('#book').animate({ 
    opacity: 0.25, 
    left: '+=50', 
    height: 'toggle' 
    }, 5000, function() { 
    // Animation complete. 
    }); 
}); 

对于全参考:和阅读功能齐全