js用for循环将小方块摆成V型方法三--小技巧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 50px;
height: 50px;
background: red;
position: absolute;
font-size: 20px;
color: #fff;
text-align: center;
line-height: 50px;
}
#box{
position: relative;
}
</style>
</head>
<body>
<input type="text" id="pt">
<button id="btn">按钮</button>
<section id="box"></section>
<script>
// 1、静态
// 2、动态
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);
var t = 0;
for (var i = 0; i < len; i++) {
// 当 i< len / 2 top 值是增加的 否则是减少的 但是 left值是一直增加的
if (i < len / 2) {
// t = i;
box.innerHTML += '<div style="left:' + i * 50 + 'px;top:' + i * 50 + 'px">'+(i+1)+'</div>';
} else {
//t = len - i - 1; // 12 -0 12- 1 12- 2
box.innerHTML += '<div style="left:' + i * 50 + 'px;top:' +(len - i - 1) * 50 + 'px">'+(i+1)+'</div>';
}
}
}
</script>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634839.html