首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过jQuery、HTML、CSS随机移动div

问通过jQuery、HTML、CSS随机移动div
EN

Stack Overflow用户
提问于 2011-05-16 03:32:49
回答 2查看 3.3K关注 0票数 0

我正在创建一个游戏,你必须跟随粒子(Div)并点击它们来“吃掉”它们。我目前遇到的问题是,我不能找到一种方法来克隆每个div,并给它一个随机的X和Y坐标值来定位它。

下面是我的代码:

代码语言:javascript
复制
var x = e.pageX;
var y = e.pageY;

function reposition(div, x, y, randomMode) {

      if(randomMode == 1) {
        x = Math.floor(Math.random() * 990);
        y = Math.floor(Math.random() * 560);
      }

      $(div).animate({"left": x + "px"}, "slow");
      $(div).animate({"top": y + "px"}, "slow");
    }

    // need to find some way to duplicate the divs and move them in random directions

    setInterval(function() {
            for(var i = 1; i < 4; i++) {

              reposition("#grabItem", 0, 0, 1);
            }
          }, 2000);
EN

回答 2

Stack Overflow用户

发布于 2011-05-16 03:51:52

代码语言:javascript
复制
//select all grab items, and since there will be multiple particles
//use a class to mark them, not an ID. This line is to capture all
//particles existing in the markup, that are not dynamically added later
var $particles = $('.grabItem');
//set your container that has all the particles
var $container = $('body');

//every two seconds add a new particle at random location
setInterval(function() {
   for(var i = 1; i < 4; i++) {
      $particles.add(CreateParticle());
      MoveParticles();
   }
}, 2000);

//creates a new particle and adds to the canvas
function CreateParticle(){
   return $('<div/>').addClass('grabItem').appendTo($container);
}

//randomly moves all the particles around
function MoveParticles() {
   $particles.each(function() {
      var x = Math.floor(Math.random() * 990);
      var y = Math.floor(Math.random() * 560);

      $(div).animate({"left": x + "px"}, "slow");
      $(div).animate({"top": y + "px"}, "slow");
   });
}

这将每两秒在随机位置添加一个新粒子,并移动所有现有粒子(包括新粒子)。如果需要精确的克隆方法,请查看jQuery的.clone()方法。

票数 4
EN

Stack Overflow用户

发布于 2011-05-16 03:50:39

jQuery中存在一个Clone方法,它是您要查找的方法吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6010702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档