【问题标题】:how can I run two different jquery functions in sequence?如何按顺序运行两个不同的 jquery 函数?
【发布时间】:2012-06-13 00:10:15
【问题描述】:

我想使用 jQuery 制作滑动图像的效果。 当我单击图像时,我想 1) 将框架宽度设为零,2) 更改为另一个图像,以及 3) 再次将框架宽度设为 100%。我使用了以下代码,无论我做什么,图像都会在帧扩展回 100% (1-> 3-> 2) 之前先发生变化。我尝试使用回调函数,但无法弄清楚。请问有什么建议吗?

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

以下是我尝试过的回调函数(我认为这是完全错误的):

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

【问题讨论】:

  • 或者有什么方法可以使用 jQuery 中的 animate() 函数更改图像 src 属性?
  • 我添加了我在上面尝试过的内容。但我认为这是完全错误的!

标签: jquery function callback sequence


【解决方案1】:

使用回调(如果可能,例如.attr() 不支持回调):

$("#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")的结果不会随时间变化)

【讨论】:

  • @user1427468:我很高兴能帮上忙 :)
【解决方案2】:

有几个 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 确保在重新动画之前加载图像。

【讨论】:

  • 就像@Tadeck 提到的,可以通过在变量中缓存帧和帧的图像来优化这段代码。
【解决方案3】:

试试下面的例子,告诉我它是否适合你:

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

完整参考:http://api.jquery.com/animate/ 并阅读完整功能

【讨论】:

    猜你喜欢
    • 2021-02-28
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多