在身体中保留附加的相对元素

时间:2016-04-24 16:55:58

标签: javascript jquery css append

我正试图在页面宽度和高度的随机位置附加div,它可以工作,但div放在页面的左下方或左侧。我已经使用了screen.width,screen.availWidth和document.body.clientWidth,我无法弄明白。我认为这部分是因为div的定位。

继承我的代码

$(document).ready(function() {
	var i = 1;
	function createDiv() {
		setTimeout(function() {
			var $newDiv = $('<div></div>').css({
				"position": "relative",
				"width": "100px",
				"height": "100px",
				"background-color": "#ccbfd9",
				"border-radius": "720px"
			});
			$($newDiv).each(function() {
			 // document.body.clientHeight
				var leftRandPos = Math.floor((Math.random() *  window.innerWidth));
		var topRandPos = Math.floor((Math.random() *  window.innerHeight));
				$(this).css('left', leftRandPos);
				$(this).css('top', topRandPos);
				$('body').append($newDiv);
			});
			i++;
			if (i < 100) {
				createDiv();
			}
		}, 250);
	}
	createDiv();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

绝对位置正是您所寻找的。

position: absolute;
top: some px;
left: some px;

进入页面中心(只是为了好玩):

 top: 50%;
 left: 50px;
 margin-left: -50px; //half of it's width
 margin-top: -50px; //half of it's height