js用for循环将小方块摆成到V(A)型方法四--小技巧

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#box{
				position: relative;
			}
			#box>div{
				position: absolute;
				top: 0;
				left: 0;
				width: 50px;
				height: 50px;
				background: red;
				font-size: 20px;
				color: #fff;
				line-height: 50px;
				text-align: center;
			}
		</style>
		<script type="text/javascript">
			window.onload = function(){
				var pt = document.getElementById('pt');
				var btn = document.getElementById('btn');
				var box = document.getElementById('box');
				btn.onclick = function(){
					box.innerHTML = "";
					var len = parseInt(pt.value);
					console.log(len)
					var lens = (len+1)/2;
					for(var i=0; i<len; i++){
						if(i<len/2){
							box.innerHTML += '<div style="left:' + i * 50 + 'px;top:' + (lens - 1 - i) * 50 + 'px">'+(i+1)+'</div>';
						}else{
							box.innerHTML += '<div style="left:' + i * 50 + 'px;top:' + (i - lens + 1) * 50 + 'px">'+(i+1)+'</div>';
							// box.innerHTML += '<div style="left:' + i * 50 + 'px;top:' + (i - parseInt(len/2)) * 50 + 'px">'+(i+1)+'</div>';
						}
					}
				}
				
			}
		</script>
	</head>
	<body>
		<input type="text" name="" id="pt" value="" /><button type="button" id="btn">A字形</button>
		<section id="box"><!-- <div>1</div> --></section>
	</body>
</html>

 

posted @ 2020-03-27 21:54  JackieDYH  阅读(3)  评论(0编辑  收藏  举报  来源