0

我在div. 我想使用某种计时器将图像移动到div.

示例 html:

<div id="Container" width="200" height="100"><img src="..."></div>
4

4 回答 4

4

我用jQuery做了一些事情。有趣的是,我从动画topleft同时开始,经过一些努力和三角学,我意识到如果你将 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两次,一次 forleft和一次 for top。因为动画没有排队,所以它们是独立动画的。

于 2012-04-19T18:17:26.247 回答
1

让我们假设您有以下 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
  })();
于 2012-04-18T20:05:41.850 回答
1

像这样的东西:

<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>
于 2012-04-19T15:09:03.003 回答
0

我想您不只是希望我们为您编写代码并希望得到答案:

您在正确的轨道上,使用计时器(查找setTimeout:),您可以在其上更改位置(使用 CSS;查找属性position,,left以及right可能margin,可能widthheight)。

如果是我,我会使用 jQuery,在这种情况下你应该查找animate.offset()...

于 2012-04-19T14:47:27.163 回答