当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - dynamic jQuery effect

问题描述:

I need to call dynamicly to jQuery effects (like 'slideDown', 'fadeIn' etc.) and then I want to do a callback like this:

$('#elemId').fadeIn(500, function(){

alert('callback function');

});

How should I call to callback in this way for example ?

var effect = 'fadeIn'; // or effect = 'slideDown'

var speed = 500;

$('#elemId')[effect](speed);

网友答案:

You were almost there, you just need to pass the callback as the second parameter, like the jQuery FX-Functions want to: http://api.jquery.com/fadeOut/

var aniFx = "fadeOut",
    aniTime = 2000,
    aniCallback = function() { alert("animation done"); };

$("#test")[aniFx](aniTime, aniCallback);

See this fiddle for a working example: http://jsfiddle.net/p4s7s/2/

网友答案:

I think the cleanest solution would be creating a wrapper function that takes a selector, effect, speed arguments and a callback function.

This might look something like:

function jQueryEffect(selector, effect, speed, callback) {
    switch(effect) {
        case "fadeIn":
            $(selector).fadeIn(speed, callback);
            break;
        // fill in other cases
    }
}
网友答案:

Could you do something like this..

var callback = function() {
     console.log('callback');   
}
var dynamic = function(effect,speed, selector, callback) {

    switch(effect) {
        case "fadeIn":
            $(selector).fadeIn(speed, function(){
                callback();
            });
            break;

        case "slideDown":
            $(selector).slideDown(speed, function(){
                callback();
            });
            break;
    }

}

$(function() {
    var effect = 'fadeIn';
    var speed = 1000;

    dynamic(effect,speed,'#test',callback);
});

http://jsfiddle.net/b5Svk/8/

There are probably better ways to do it but mehhhhh!

网友答案:

You can use if/switch statement if you are aware of all the effect names:

var effect = 'fadeIn'; 
var speed = 500;

if (effect === "fadeIn")
    $('#elemId').fadeIn(speed);
else {
    $('#elemId').slideDown(speed);
}

You can also try looking into calling dynamic function names in javascript. Check out http://derek.io/blog/2009/dynamic-function-names-in-javascript/

分享给朋友:
您可能感兴趣的文章:
随机阅读: