鑑於比你的容器的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
});
});
UPDATE:
更新了代碼以容納幾個.t-shirt-design
元素
更新2:
你也有你的HTML代碼中的錯誤,一個HTML元素只能有一個ID,你在你的容器html元素有兩個,具體如下:
<div id="tshirts-designs homepage">
代替它只是一個,正確的是:
<div id="homepage">
更新3:
在你的頁面來看,我調整我的代碼,以更好地滿足您的要求(您可拖動的元素具有不同的寬度和高度),所以儘量我更新的代碼代替,最好在上執行此代碼事件,而不是.ready
,因爲我們需要加載的圖像,以便在div高度和寬度是正確的,所以更換你的下面一行:
$(document).ready(function() {
這一個:
$(window).load(function() {
什麼是可拖動項目的高度? – Nelson