我在div
里面有一个图像。 我想使用某种计时器将图像移动到div
内的各个位置。
示例 html:
<div id="Container" width="200" height="100"><img src="..."></div>
我用jQuery做了一些事情。 有趣的是,我从同时制作top
和left
动画开始,经过一些努力和三角学,我意识到如果你将x和y分量分开,在div中弹跳的动画就会变得容易得多。
演示:http://jsfiddle.net/jtbowden/DcgwR/
这是一个可以处理多个元素的版本:
演示:http://jsfiddle.net/jtbowden/DcgwR/2/
关键代码段是:
// Parameters
// img: jQuery element (not necessarily img)
// speed: in px/millisecond
// max: maximum distance to travel
// dir: 'left' or 'top'
function bounce(img, speed, max, dir) {
speed += ((Math.random() * varSpeed) - (varSpeed / 2));
speed = speed < minSpeed ? minSpeed : (speed > maxSpeed ? maxSpeed : speed)
var time = max / speed;
var position = img.position();
var target = (position[dir] < 2) ? max : 0;
var style = {
queue: false
};
style[dir] = target;
img.animate(style, {
duration: time,
queue: false,
easing: "linear",
complete: function() {
bounce(img, time, max, dir);
}
});
}
maxSpeed
、 minSpeed
、 varSpeed
是全局定义的(以 px/ms 为单位),varSpeed
是每次弹跳时速度变化的程度。 我有一个单独的函数startBounce
它调用bounce
两次,一次用于left
,一次用于top
。 由于动画未排队,因此它们独立进行动画处理。
让我们假设您有以下 HTML:
<div id="container" style="width:500px;height:500px">
<img src="foo.gif" width="50" height="50">
</div>
现在使用 jQuery,你可以做到:
<script>
;(function() {
var img = $("#container img");
img.css({ position: "absolute" });
img.animate({ left: 50, top: 50 });
img.animate({ left: 100, top: 100 });
// and so on
// or if you just want to position it without animation
img.css({ left: 50, top: 50 });
// some timeout or similar
img.css({ left: 100, top: 100 });
// and so on
})();
像这样:
<script>
function moveit()
{
var animatedImg = document.getElementById( "animate" );
var top = animatedImg.offsetTop;
var left = animatedImg.offsetLeft;
top++;
left++;
if ( top > 100 )
{
top = 0;
}
if ( left > 200 )
{
left = 0;
}
animatedImg.setAttribute( "style", "position: relative; top: " + top + "px; left: " + left + "px;" );
setTimeout( moveIt, 1000 );
}
</script>
...
<body onload="moveIt()">
<div>
<img src="imageSource" id="animate" />
</div>
我想你不只是希望我们为你编写代码,而是想要答案:
你走在正确的轨道上,使用计时器(查找:setTimeout
),你可以在上面更改位置(使用CSS;查找属性position
,left
,right
,可能还有margin
,可能是width
和height
)。
如果是我,我会使用 jQuery,在这种情况下,您应该查找animate
,.offset()
......