<!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> </head> <body> <button>按钮1</button> <button>按钮2</button> <button>按钮3</button> <button>按钮4</button> <button>按钮5</button> <script> // 先得到所有按钮,将里面每个按钮遍历出来,分别给每一个按钮添加点击 // 事件,先在事件处理函数中把所有的样式干掉,然后在设置自己的样式 var btn = document.getElementsByTagName("button") for (let i = 0; i < btn.length; i++) { btn[i].onclick = function () { console.log(i); for (let j = 0; j < btn.length; j++) { btn[j].style.backgroundColor = "" } btn[i].style.backgroundColor = 'pink' } } </script> </body> </html>