开发者

When I wrap my animation effect in a function, it stops working. Can anyone tell me why?

I copied the css and javascript into jsfiddle, but I don't know what to put in html, anyway, I'm trying to get a single image to pulse, the problem is it is only defined as a class, and I'm ha开发者_高级运维ving trouble with it. When I have it alone as it's own function it works fine http://jsfiddle.net/EQs9N/, but when I wrap it in an invisible function (or whatever its called) the animation stops firing http://jsfiddle.net/EQs9N/1/. Does this have something to do with me animating a class? Is there anyway to define it as an object, and would this help? Thanks


You are declaring a function A, but you aren't calling the function.

(function(){
    ...
})()

That will create an anonymous function (is that the term you were looking for) and execute it. I'm not sure why you need to wrap it in this case, $(document).ready() should be sufficient.

Side note on jsfiddle usage:
In jsfiddle, you can select onDomReady instead of onLoad from the framework dropdowns to automatically wrap your javascript in $(document).ready() making your invokation of $(document).ready() redundant. The option onLoad will wrap it in $(window).load()

If you select "no wrap", then jsfiddle will only surround it with the necessary script tags and then put that in the head or the body, depending on the selected option.


$(document).ready(function() { is the way jquery delays any code execution to after the page is fully loaded.

If you wrap this part of the code within a function, it won't work anymore and the code would only be called when you call the function. That's why it doesn't work when you wrap your code.

See this tuto for the good use of $(document).ready


In your second jsfiddle you're defining a function (function A) but not actually calling it.

If you change your code slightly and pass A to document.ready (instead of passing an anonymous function) you should find that it works:

function A(){
    if (1 == 1){
        function pulsate() {
            $(".image2_template").
              animate({opacity: 0.1}, 1500, 'linear').
              animate({opacity: 1}, 1500, 'linear', pulsate);
          }
        pulsate();
    } else {
        $('.image2_template').animate({
             opacity: 0,
        });
        $('.text3_template').animate({
            opacity: 0,
        });
    }
}

$(document).ready(A);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜