The picture is pretty much explanatory by itself. The div "behind" contains a bunch of little square photos that I want to animate smoothly. I'm really not good with jQuery animations, could anyone hel开发者_JAVA技巧p me out with this?
(Window is fixed, pictures move "inside" it, animating forever since the page load)
You could do something like this
markup:
<div id="mask">
<img id="pic" alt="my img" src="http://www.destination360.com/north-america/us/idaho/images/s/idaho-sawtooth-mountains.jpg">
</div>
css:
#mask{
overflow:hidden;
width:100px;
height:100px;
position:absolute;
border:5px solid #000000;
}
#mask img{
border:none;
position:absolute;
}
js:
$('#pic').animate({left:-200},3000).animate({top:-50},3000); /* and so on... */
fiddle:
http://www.jsfiddle.net/steweb/YHAZ9/
Edit (looping it forever) http://www.jsfiddle.net/steweb/YHAZ9/4/
I'm a fan of SIN/COS functions, so let me share with you my shot at this problem.
The idea is to have a function that runs forever, and as soon as possible so that the animation is smooth. I use a sin/cos functions to determine the new x (left) and y (top) coordenates of the div, and I have a series of parameters that allow the configuration of the speed and range of the animation.
Just paste this into an HTML file and test it in your browser.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div id="stuff" style="background: red; width: 200px; height: 200px; margin: auto; position: relative;">
a b c<br />
d e f<br />
g h i<br />
j k l<br />
</div>
<script>
var start = new Date();
var x_speed = 0.001, // bigger ---> faster
y_speed = 0.01, // bigger ---> faster
x_multiplier = 300, // how far away I can go on the X axis
y_multiplier = 20, // how far away I can go on the Y axis
x_offset = 0,
y_offset = 0;
function animate() {
var now = new Date();
var elapsed_time = now - start;
var x = Math.sin((elapsed_time)*x_speed) * x_multiplier + x_offset;
var y = Math.cos((elapsed_time)*y_speed) * y_multiplier + y_offset;
$("#stuff").css({
left : x,
top : y
});
setTimeout(animate, 0);
}
setTimeout(animate, 76);
</script>
</body>
</html>
For how long? After a click?
I'm not behind my own computer right now, but try something like this:
This is for after a click:
$("#frame").click(
function(){
$("#photo").animate({"left": "-=100px"}, function(){
$("#photo").animate({"top": "-=100px"}, function(){
$("#photo").animate({"left": "=100px"});
});
});
});
And so forth, after each line you can put a new line, like i did in line 3 and 4 from the code. This way the photo behind moves in a square.
Just a suggestion, don't know if this is exactly what you want.
EDIT: Btw, you can only go left, right or up and down, what might smoothen your animation is to grow the photo and shrink it. Therefore you need for instance the "width" parameter. Check the jQuery site here.
精彩评论