杨辉三角需要考虑内容
- 杨辉三角中的各部分数据是如何形成的
- 打印输出过程中,每行到底需要空多少格,浏览器中直接居中展示即可,如果是文本中该如何显示
- 未控制单个数字长度时候,展示出来曲线效果如何解决
- 前几行都是一位数字,出现多位数字时候,未控制数字每个数字长度,出现重叠现象该怎么办
下面代码可直接拷贝到文本文件中,将文本文件后缀修改成.html,在浏览器中打开即可显示效果
使用HTML展示杨辉三角
<html>
<head>
<title>杨辉三角</title>
<style>
#main {
text-align: center;
}
#dis {
margin-top: 10px;
background-color: #a2f2d0;
}
.label-v {
text-align: center;
display: inline-block;
}
</style>
</head>
<body>
<div id="main">
<div>
<input id="number" type="number" value="1" style="font-weight: bold; height: 30px;" onchange="print();" />
</div>
<div id="dis">
</div>
</div>
</body>
<script>
function print() {
document.getElementById('dis').innerText = '';
var num = document.getElementById("number").value;
var list = [];
if (num > 0) {
var firstRow = [];
firstRow.push(1);
list.push(firstRow);
}
if (num > 1) {
var secondRow = [];
secondRow.push(1, 1);
list.push(secondRow);
}
for (var i = 2; i < num; i++) {
var currentInts = getInt(list[i - 1], i);
list.push(currentInts);
}
var lastRow = list[list.length - 1];
var max = lastRow[Math.floor(lastRow.length / 2)];
var maxLength = (max + '').length;
for (var i = 0; i < list.length; i++) {
var rowDiv = document.createElement('div');
for (var j = 0; j < list[i].length; j++) {
var cell = document.createElement('label');
cell.innerText = list[i][j];
cell.style = "width: " + (10 * maxLength) + "px";
cell.className = 'label-v';
rowDiv.appendChild(cell);
if (j != list[i].length - 1) {
rowDiv.appendChild(createSpace());
}
}
document.getElementById('dis').appendChild(rowDiv);
}
};
function createSpace() {
var spaceDom = document.createElement('label');
spaceDom.innerText = ' ';
spaceDom.style = 'text-align: center';
return spaceDom;
}
function getInt(pre, current) {
var currentInts = [];
currentInts.push(1);
for (var i = 0; i < current; i++) {
if (i < pre.length - 1) {
var val = pre[i] + pre[i + 1];
currentInts.push(val);
}
else {
currentInts.push(pre[i]);
}
}
return currentInts;
}
window.onload = print();
</script>
</html>