js用for循环将小方块摆成V型方法二--小技巧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.block {
position: absolute;
left: 0;
top: 0;
width: 50px;
height: 50px;
font-size: 22px;
line-height: 50px;
text-align: center;
color: #fff;
background: #ff6600;
}
</style>
</head>
<body>
<p id="no"><input type="text" name="" id="pt" value="" /><button type="button" id="btn">生成v</button></p>
<div id="blockContainer"></div>
<script>
let block_width = 50;
function makeVictor(amount) {
// 先判断一下amout的奇偶性
// 取中间数
let number_middle = (amount + 1) / 2
//创建html字符串
let html = "";
let position_x = 0;
let position_y = 0;
for (let i = 0; i < amount; i++) {
position_x = i * block_width;
position_y = (number_middle - 1 - Math.abs(number_middle - 1 - i)) * block_width;
// console.log(position_x)
html += '<div class="block" style="left:' + position_x + 'px;top:' + position_y + 'px;">'+ i +'</div>';
console.log(position_y)
}
document.getElementById("blockContainer").innerHTML = html;
}
// 根据输入的数字生成不同数量的正方块V字形状
var pt = document.getElementById('pt');
var btn = document.getElementById('btn');
var pNo = document.getElementById('no');
btn.onclick = function(){
makeVictor(Number(pt.value));
pNo.style.display = 'none';
}
</script>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634842.html