简体   繁体   中英

why this jQuery animation loop doesn't work?

<script>
function swim() {

    $("#ship").animate({left: "-=-540px"}, 3000, function() {

        $("#ship").css("-moz-transform", "scaleX(-1)");
        $("#ship").css("-o-transform", "scaleX(-1)");
        $("#ship").css("-webkit-transform", "scaleX(-1)");
        $("#ship").css("transform", "scaleX(-1)");
        $("#ship").css("filter", "FlipH");
        $("#ship").css("-ms-filter", "FlipH");
        $("#ship").animate({left: "-=540px"}, 3000);
        swim();

        })

    }


    swim();

</script>

When I use only document.ready works fine, but stops after an attempt to turn it to a loop. There must be a syntax bug somewhere but I can't figure out where.

EDIT: nvm. It was the case of putting the script to <head> instead of <body> .

There's a reason why it needs the document ready wrapper. A "normal" function isn't an equal replacement for it. If you call the function before the DOM is ready, the #ship selector doesn't match anything, the animation doesn't run, and the callback isn't executed.

Call the function in a document ready event:

$( swim );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM