最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery random position to multiple divs - Stack Overflow

programmeradmin3浏览0评论

that is my code / (it works) but i want everyone div to be with unique position coordinates. Now script get the first and others move to him place. How can be possible to fix this problem? I tryed a .each function but there wasn't any results. I think this will be easy but i'm to too good in jquery/javascript.

$('#latestblock').animate({
  top: newY,
  left: newX
}, 500, function() { });

I think here must be in loop but dont know how to do it.

that is my code http://jsfiddle/BREvn/2/ (it works) but i want everyone div to be with unique position coordinates. Now script get the first and others move to him place. How can be possible to fix this problem? I tryed a .each function but there wasn't any results. I think this will be easy but i'm to too good in jquery/javascript.

$('#latestblock').animate({
  top: newY,
  left: newX
}, 500, function() { });

I think here must be in loop but dont know how to do it.

Share Improve this question asked Jan 15, 2013 at 13:58 Stoyan ZdravkovStoyan Zdravkov 951 silver badge6 bronze badges 3
  • IDs must be unique on each document, use class instead! – A. Wolff Commented Jan 15, 2013 at 14:02
  • you could keep the position of each div in an array, then check if the new random position overlays an existing div, if not position the div, else rerun randomizing code. – ppp Commented Jan 15, 2013 at 14:04
  • Do you want the three div's to move simultaneously? – Ferry Kobus Commented Jan 15, 2013 at 14:04
Add a ment  | 

3 Answers 3

Reset to default 2

Something like this?

http://jsfiddle/BREvn/5/

I renamed the id to a class and created an infinite loop. Also send the object into the moveRandom function 'moveRandom(obj)' and after de animation finishes, recall the moveRandom function with itself.

$('.latestblock').each(function() {
    moveRandom($(this));
});

You can't give the same id to more than one element.

You could use a class

<div id='container'>
  <div class='latestblock'></div>
  <div class='latestblock'></div>
  <div class='latestblock'></div>
</div>

and then use each to animate all elements :

$('.latestblock').each(function(){ // <= iterates on all blocks
   moveRandom($(this)); // <= pass the block to the moveRandom function
});

Complete demo

Here is the updated and working version: http://jsfiddle/BREvn/4/

An ID must be unique, you cannot have 3 elements with the same id='latestblock'

I also called the function three times and made sure the function was using that parameter passed in.

moveRandom('#latestblock1');
moveRandom('#latestblock2');
moveRandom('#latestblock3');
发布评论

评论列表(0)

  1. 暂无评论