随机左,顶部位置,jquery,javascript

时间:2012-10-08 18:02:17

标签: javascript jquery html

我有一个div元素列表,它是可拖动的项目。

我需要做的是,所有元素,我将生成随机的顶部和左侧位置,这将在我的容器范围内,但我不知道该怎么做:)

容器div是:宽度:800px;身高:500px;

我的js现在就像:

var randomTopPos = Math.floor(Math.random() * (600 / 2));
var randomLeftPos = Math.floor(Math.random() * (5));

$(".t-shirt-design").css({
    'top' : randomTopPos,
    'left': randomLeftPos
});

4 个答案:

答案 0 :(得分:1)

鉴于您的容器ID为container且您的可拖动ID为dragid,您可以执行以下操作:

ctop = $('#container').offset().top;  // container top
cleft = $('#container').offset().left;// container left
cheight = $('#container').height();   // container height
cwidth = $('#container').width();     // container width

$(".t-shirt-design").each(function() {
   dragheight = $(this).height(); //your draggable height
   dragwidth  = $(this).width(); // your draggable width
   randomtop = ctop + Math.floor((Math.random()* (cheight - dragheight))+1);
   randomleft = cleft + Math.floor((Math.random()* (cwidth - dragwidth))+1);
   $(this).css({
     'top' : randomtop,
     'left': randomleft
   });
});

更新
更新了代码以容纳多个.t-shirt-design元素

UPDATE 2
你的html代码中也有错误,html元素只能有一个id,你的容器html元素中有两个,如下所示:

<div id="tshirts-designs homepage">

只替换一个,正确的是:

<div id="homepage">

更新3
查看您的页面,我调整代码以更好地满足您的要求(您的可拖动元素具有不同的宽度和高度),因此请尝试使用我的更新代码,更好地在window.load事件上执行此代码,而不是.ready,因为我们需要加载图像,因此div高度和宽度是正确的,所以请替换以下行:

$(document).ready(function() {

这个:

$(window).load(function() {

答案 1 :(得分:0)

$(".t-shirt-design").each(function(){
   var $t = $(this);
   var randomTopPos = Math.floor(Math.random() * (containerHeight-$t.width()));
   var randomLeftPos = Math.floor(Math.random() * (containerWidth-$t.height()));
   $t.css({
      'top': randomTopPos,
      'left':randomLeftPos
   });
});

containerHeightcontainerWidth替换为真实值。确保项目位于容器内并具有position:relative;

答案 2 :(得分:0)

var randomTopPos = Math.floor(Math.random() * (600 / 2));
var randomLeftPos = Math.floor(Math.random() * (5));

$(".t-shirt-design").css({
    'top' : Math.floor(Math.random() * $(this).parent().height() - itemHeight),
    'left': Math.floor(Math.random() * $(this).parent().width() - itemWidth) 
});

答案 3 :(得分:0)

看起来你正走在正确的道路上......

Math.random()正在生成介于0和1之间的数字。

您可以将这些数字乘以您想要的范围,将范围更改为0范围。

然后将这些值指定为上/左位置。

一些注意事项:

  1. 元素的宽度和高度是多少?如果它们不同,您可能需要根据给定对象的宽度/高度生成每个位置。否则,将它们视为常数。如果您有50x50px项目,则最大'顶部'为450,最大'左'为750,因此乘以450和750而不是500和800。

  2. 您正在将这些值应用于CSS类,如果您为每个项目分配了相同的类,则不会将它们随机化,而是将它们放在同一个位置。您可能希望执行以下操作:

    $(".t-shirt-design").each(function(e){
        // Generate random numbers
        e.css({
            'top' : randomTopPos,
            'left': randomLeftPos
        });
    });