如何实现以上次最后盒子尺寸为起点新增递增尺寸的盒子?
实现连续递增尺寸的盒子功能
你的思路完全正确,通过获取boxCollection的最后一个子元素尺寸作为新盒子的起始基准,就能实现「再次添加时以上次最后一个盒子尺寸为起点递增」的需求。
具体实现方案
- 在
createBoxes函数中先判断当前是否已有盒子:- 若存在已创建的盒子,提取最后一个盒子的宽/高(因是正方形,取其一即可)作为新盒子的起始尺寸
- 若没有盒子,使用默认的30px作为起始尺寸
- 循环创建新盒子时,基于起始尺寸每次累加10px的增量
- 注意将输入框的值转为数字,避免字符串运算导致的异常
修改后的完整代码
function getRandomHexColor() { return `#${Math.floor(Math.random() * 16777215).toString(16)}`; } const input = document.querySelector("#controls>input"); const createBtn = document.querySelector("button[data-create]"); const destroyBtn = document.querySelector("button[data-destroy]"); const boxCollection = document.querySelector("#boxes"); const createBoxes = () => { const amount = Number(input.value); // 获取起始尺寸:有盒子则取最后一个的宽度,无盒子则用默认30px let startSize = boxCollection.lastChild ? parseInt(boxCollection.lastChild.style.width) : 30; for (let i = 0; i < amount; i += 1) { const newBox = document.createElement("div"); const currentSize = startSize + 10 * i; newBox.style.height = `${currentSize}px`; newBox.style.width = `${currentSize}px`; newBox.style.background = getRandomHexColor(); boxCollection.appendChild(newBox); } }; createBtn.addEventListener("click", createBoxes); const destroyBoxes = () => { boxCollection.innerHTML = ""; }; destroyBtn.addEventListener("click", destroyBoxes);
补充说明
- 用
parseInt解析最后一个盒子的宽度值,确保得到数字类型的尺寸数据 - 将
insertAdjacentElement("beforeend")替换为更简洁的appendChild,实现效果完全一致 - 新增
amount的类型转换,避免输入非数字内容时出现逻辑异常
内容的提问来源于stack exchange,提问作者Vincent Słomiński
相关产品推荐
相关产品推荐

