JavaScript动态设置左侧和顶部位置

时间:2015-10-17 17:52:28

标签: javascript jquery

我有这个问题。我希望实现元素的设置和左侧位置,这是我无法解决的问题。任何有工作解决方案的人都要感谢。

$(document).ready(function (){

//lets assign a value to a variable, but in my case the value is obtained from different part but that has no problem.
//Note in real case this value changes.
var number = 4;


//we create a function to count the top and left dimensions
//Note the values given are exactly as I want. the param given is number of current rect and second is total rect to be drawn.
 function dim(i,a)
 {
	 var top = '';
	 if((i%2)==0){top = 0;}
	 else if ((i%2)==1){top = ((document.documentElement.clientHeight)*1/3)/2; top = Math.floor(top);}
	 //We have gotten the top value if odd 0px if even halfway our container.
	 //Now for the left.
	 var y = (((a/2)+1)-i);
		y = y*(-1);
		var W = document.documentElement.clientWidth;
		var left = Math.floor(((W/2)+(30*y)));
		//alert(top+' , '+left);
		return ([top,left]);
 }
 function draw()
 {
	 //This is the main function.
	 for (i = 1; i <= number; i++ )
	 {
		 
		 
		var cd = document.createElement('div');
		var node = document.createTextNode("This is new.");
		cd.appendChild(node);
		cd.style.width = '30px';
		cd.style.background = 'rgb('+10*i+','+20*i+','+15*i+')';
		cd.setAttribute ('position','relative');
		var x = Math.floor(((document.documentElement.clientHeight)*1/3)/2);
		cd.style.height = x+'px';
		cd.className = 'rect'+i;
		var di = dim(i,number);
		cd.style.top = di[0]+'px';
		cd.style.left = di[1]+'px';
		document.body.appendChild (cd);
	 }
 }
 draw();
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>

我不希望它出现在同一条线上,没有左右对齐。感谢。

0 个答案:

没有答案