如何通过输入框动态修改单个新增按钮的宽高?
搞定每个按钮独立设置宽高的问题
为啥原来的代码只改最后一个按钮
你每次点「添加按钮」创建新按钮时,都会给apply按钮再绑一次点击事件,而且事件里的按钮变量只会指向最后一次创建的按钮。不管你选中哪个按钮,最后触发「应用」时,代码只会去找最后那个按钮改样式。
修复方法
你已经写了myFunction来获取当前选中元素的ID,刚好可以利用这个ID定位要修改的按钮。同时要把apply的事件绑定移到创建按钮的函数外面,只绑一次就行。
修改后的完整代码
HTML
<body onclick="myFunction()"> <div class="container"> <div id="preview"> <div class="input"> <label for="width">宽度</label> <input type="text" id="width" name="width" placeholder="比如150px" autocomplete="off"> <label for="height">高度</label> <input type="text" id="height" name="height" placeholder="比如40px" autocomplete="off"> <button id="apply">应用</button> <input type="text" id="number" value="" style="display: none;"> <input type="button" onclick="buttonClick();" id="addbuton" value="添加按钮"> </div> <p>当前激活元素ID: <em id="output-element"></em></p> </div> </div> </body>
CSS
.input { display: inline-grid; gap: 8px; } .container { display: flex; } .name { margin: 4px 0; cursor: pointer; }
JavaScript
let i = 0; // 提前拿到apply按钮,只绑一次事件 const applyBtn = document.getElementById("apply"); // 绑定apply的点击事件,只执行一次 applyBtn.addEventListener("click", () => { // 获取当前选中的按钮ID const activeBtnId = document.getElementById("output-element").textContent; // 不是我们创建的Button就直接返回 if (!activeBtnId || !activeBtnId.startsWith("Button")) return; const targetBtn = document.getElementById(activeBtnId); const width = document.getElementById("width").value; const height = document.getElementById("height").value; // 有输入值才修改对应样式 if (width) targetBtn.style.width = width; if (height) targetBtn.style.height = height; }); function buttonClick() { i++; const btnId = `Button${i}`; document.getElementById('number').value = btnId; const newButton = document.createElement("button"); newButton.id = btnId; newButton.className = "name"; const preview = document.getElementById('preview'); newButton.textContent = btnId; newButton.style.display = "block"; newButton.style.width = "100px"; newButton.style.height = "32px"; preview.appendChild(newButton); }; function myFunction() { const activeId = document.activeElement.id; document.getElementById("output-element").textContent = activeId; };
核心改动点
- 事件只绑一次:把
apply的点击事件移到buttonClick外面,避免重复绑定导致的逻辑混乱。 - 用选中ID定位按钮:点击「应用」时,通过当前显示的激活元素ID找到要修改的按钮,不再依赖创建时的局部变量。
- 体验优化:给输入框加了占位提示,按钮加了间距和鼠标样式,操作更顺手。
- 边界判断:只处理我们创建的以
Button开头的元素,防止误改其他元素。
内容的提问来源于stack exchange,提问作者Papillon
相关产品推荐
相关产品推荐

