js用for循环将小方块摆成V型方法一--小技巧

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#list {
				position: relative;
				list-style: none;
			}

			li {
				position: absolute;
				top: 0;
				left: 0;
				width: 50px;
				height: 50px;
				font-size: 22px;
				line-height: 50px;
				text-align: center;
				color: #fff;
				background: red;
			}
		</style>
		<script type="text/javascript">
			// 生成v形,并填入数字
			window.onload = function() {
				var btn = document.getElementById('btn');
				var pt = document.getElementById('pt');
				var aUl = document.getElementById('list');
				var aLi = document.getElementsByTagName('li');

				function li_pos(mid) {
					console.log(aLi);
					for (var i = 0; i < aLi.length; i++) {
						aLi[i].style.left = i * 50 + 'px';
						aLi[i].style.top = (mid - 1 - Math.abs(mid - 1 - i)) * 50 + 'px';
					}
				}

				btn.onclick = function() {
					var i = Number(pt.value);
					// console.log(i);
					aUl.innerHTML = "";
					for (var j = 1; j <= i; j++) {
						// console.log(typeof i);
						aUl.innerHTML += '<li>' + j + '</li>';
					}
					
					var middle = (i + 1) / 2;
					li_pos(middle);


				}



			}
		</script>
	</head>
	<body>
		<p><input type="text" name="" id="pt" value="" placeholder="请输入个数" /><button type="button" id="btn">v字型</button></p>
		<!-- <div>1</div> -->
		<div id="content">
			<ul id="list">
				<!-- <li>1</li> -->
			</ul>
		</div>
	</body>
</html>

 

posted @ 2022-07-14 01:38  JackieDYH  阅读(8)  评论(0编辑  收藏  举报  来源