1

我正在尝试使用 jQuery 从页面中删除对象。我还想为删除设置动画。目标是使元素fadeOut(),等待一秒钟,然后remove()。但它似乎拒绝等待删除元素,即使我在 setTimeout() 函数中使用它也是如此。我怎样才能让一个元素fadeOut(),然后remove()呢?

$("button").click(function() {
    $(this).fadeOut();
    setTimeout(function() { $(this).remove();}, 1000);
});
4

5 回答 5

8

仔细阅读手册:http: //api.jquery.com/fadeOut/

fadeOut() 方法有一个回调,在fadeOut 完成后调用。要使用它:

$("button").click(function() {
    $(this).fadeOut(function() { $(this).remove();});
});

在fadeOut 完成后,在移除元素之前没有理由等待一秒钟,因为元素在移除时将是不可见的。

于 2012-05-22T14:37:31.370 回答
7

在您的超时功能中,this并不是您认为的那样 - 它实际上是全局window对象。

无论如何(没有双关语),您应该使用“完成回调”:

$("button").click(function() {
    $(this).fadeOut('slow', function() {
        $(this).remove();
    });
});

永远不要混合setTimeout和动画队列。可以将两者交错,即让完成回调启动计时器,或让计时器启动动画,但假设您可以同时启动 1000 毫秒动画和 1000 毫秒计时器并让它们同时完成,这是绝对不行的.

编辑固定代码 - 不需要self在完成回调中,我还在想setTimeoutthis当我写的时候!

于 2012-05-22T14:37:03.547 回答
1
$('button').click(function(){
    $(this).fadeOut(function(){$(this).remove()});
});​

演示

于 2012-05-22T14:40:39.793 回答
0

为什么不直接使用淡出的回调呢?

$("button").click(function() {
    $(this).fadeOut(function(){$(this).remove();});
});
于 2012-05-22T14:39:51.007 回答
0

试试这个,也许它有帮助:

$("button").click(function() {
    (function(that) {
        that.fadeOut();
        setTimeout(function() {
            that.remove();
        }, 1000);
    })($(this));
});
于 2012-05-22T15:59:57.690 回答