Случайное перемещение div через jQuery, HTML, CSS - PullRequest
0 голосов
/ 15 мая 2011

Я создаю игру, в которой вы должны следить за частицами (делителями) и нажимать на них, чтобы «съесть» их. Проблема, с которой я сталкиваюсь в настоящее время, заключается в том, что я не могу найти способ клонировать каждый div и дать ему случайное значение координат X и Y для его позиционирования.

Вот мой код:

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);

Ответы [ 2 ]

4 голосов
/ 15 мая 2011
//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 () .

0 голосов
/ 15 мая 2011

В jQuery существует метод Clone , это то, что вы ищете?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...