Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - jQuery to animate image from left to right?

I have a Bee image and I want to animate it using jQuery.

The idea is to move the image from left (outside of screen) to right (outside of screen) to create an effect like it's flying.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your bee needs to be absolutely positioned, something like this:

<div id="b" style="position:absolute; top:50px">B</div>

I've used a div here, but it could just as well be an <img> tag. As meo pointed out, don't forget the top attribute, because some browsers don't work without it. Then you can animate it:

$(document).ready(function() {
    $("#b").animate({left: "+=500"}, 2000);
    $("#b").animate({left: "-=300"}, 1000);
});

Here is a jsfiddle demo.

If you want to have a continuous animation as Hira pointed out, put the animation code in functions, make sure the left and right movement is the same, and use the onComplete option of animate() to call the next animation:

function beeLeft() {
    $("#b").animate({left: "-=500"}, 2000, "swing", beeRight);
}
function beeRight() {
    $("#b").animate({left: "+=500"}, 2000, "swing", beeLeft);
}

beeRight();

And the fiddle for that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...