$(this)在animate()回调中,但是使用setTimeout

时间:2014-03-11 11:32:07

标签: javascript jquery animation settimeout

jQuery docs明确说明

  

如果提供,则完成回调函数   动画完成。这对于串联不同可能很有用   动画按顺序组合在一起。回调不会发送任何   参数,但这被设置为动画的DOM元素。

因此,这很好用:

$("button").click(function () {
    $(this).next("div").stop(true, true).animate({
        "opacity": 1,
            "top": "36px"
    }, 600, function () {
            $(this).fadeOut("slow", function () {
                $(this).css({
                    "top": 0,
                        "display": "block",
                        "opacity": 0
                });
            });
    });
});

$(this)的下一个兄弟是一个div,它首先被动画化,然后通过回调它再次淡出。但是...!

在后备中使用setTimeout时,这将不起作用。请参阅此fiddle

$("button").click(function () {
    $(this).next("div").stop(true, true).animate({
        "opacity": 1,
            "top": "36px"
    }, 600, function () {
        setTimeout(function () {
            $(this).fadeOut("slow", function () {
                $(this).css({
                    "top": 0,
                        "display": "block",
                        "opacity": 0
                });
            });
        }, 2000);
    });
});

我需要使用$(this).next(),因为我将在页面上有多个按钮。如何保持2秒的延迟,但仍然使用$(this)选择器?

3 个答案:

答案 0 :(得分:3)

对于jQuery的动画方法,您可以使用delay()

$("button").click(function () {
    $(this).next("div").stop(true, true).animate({
        "opacity": 1,
        "top": "36px"
    }, 600, function () {
        $(this).delay(2000).fadeOut("slow", function () {
            $(this).css({
                "top": 0,
                "display": "block",
                "opacity": 0
            });
        });
    });
});

JSFiddle

注意:setTimeout()对您不起作用的原因是因为this并未引用您认为的元素,它指的是到window。为此,您需要先创建对this的引用:

JSFiddle

答案 1 :(得分:1)

也有点神奇。您可以将“this”绑定到超时功能。

http://jsfiddle.net/h6E6z/5/

setTimeout(function () {
    $(this).fadeOut("slow", function () {
        $(this).css({
            "top": 0,
            "display": "block",    
            "opacity": 0
        });
    });
}.bind(this), 2000);

答案 2 :(得分:1)

你总是可以将$(this)存储在变量中并在超时函数中使用它(我使用" $"在存储dom元素的变量前面 - 这当然是完全可选的,我就这样喜欢......):

$("button").click(function () {
    $(this).next("div").stop(true, true).animate({
        "opacity": 1,
            "top": "36px"
    }, 600, function () {
        var $next_div = $(this);
        setTimeout(function () {
            $next_div.fadeOut("slow", function () {
                $next_div.css({
                    "top": 0,
                        "display": "block",
                        "opacity": 0
                });
            });
        }, 2000);
    });
});