JavaScript原生代码实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
window.onload = function () {
//根据标签获取body元素
var body = window.document.getElementsByTagName("body")[0];
//规定初始值
var width = window.innerWidth, height = window.innerHeight, left = 10, top = 10;
while (true) {
//创建div加入到body中
var divElement = window.document.createElement("div");
divElement.style.position = "absolute";
divElement.style.border = "1px solid blue";
divElement.style.width = width + "px";
divElement.style.height = height + "px";
divElement.style.left = left + "px";
divElement.style.top = top + "px";
//改写数值
left += 5;
top += 5;
width -= 10;
height -= 10;
body.appendChild(divElement);
if (width <= 0 || height <= 0) {
break;
}
}
}
</script>
</head>
<body>
</body>
</html>
jQuery实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
</style>
<script src="script/jquery-3.2.1.js"></script>
<script>
$(function () {
var left = 0;
var top = 0;
var width = window.innerWidth;
var height = window.innerHeight;
while (true) {
var divElement = $("<div></div>");
divElement.css({"border":"1px solid blue","position":"absolute", "left": left + "px", "top": top + "px", "width": width + "px", "height": height + "px" });
left += 5;
top += 5;
width -= 10;
height -= 10;
divElement.appendTo($("body"));
if (width <= 0 || height <= 0) {
break;
}
}
})
</script>
</head>
<body>
</body>
</html>