如何使用JavaScript点击一个按钮修改其他按钮的背景颜色
完整实现代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>按钮联动改色</title> </head> <body> <button class="btn">按钮1</button> <button class="btn">按钮2</button> <button class="btn">按钮3</button> <button class="btn">按钮4</button> <script> // 获取全部4个按钮元素 const btnList = document.querySelectorAll('.btn') btnList.forEach((btn, idx) => { btn.addEventListener('click', () => { // 点击按钮1的逻辑:对应索引为0 if (idx === 0) { btnList[1].style.backgroundColor = 'black' btnList[2].style.backgroundColor = 'red' btnList[3].style.backgroundColor = 'yellow' } // 其余按钮点击逻辑可按下方格式扩展,按需设置对应按钮的颜色即可 // 例:点击按钮2的逻辑 // if(idx === 1) { // btnList[0].style.backgroundColor = 'xxx' // btnList[2].style.backgroundColor = 'xxx' // btnList[3].style.backgroundColor = 'xxx' // } }) }) </script> </body> </html>
- 上述代码已经实现你提到的点击按钮1后其余三个按钮分别变为黑色、红色、黄色的需求,可直接运行
- 代码采用原生HTML+JS实现,不需要引入任何第三方依赖
- 通过索引区分不同按钮,后续扩展其他按钮的点击改色逻辑成本极低
内容的提问来源于stack exchange,提问作者black
相关产品推荐
相关产品推荐

