点击变颜色
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>点击变颜色</title> <!-- IMPORT CSS --> <style> * { margin: 0; padding: 0; } html, body { /* width: 100%; */ height: 100%; overflow: hidden; } button { padding: 40px; line-height: 40px; } </style></head><body> <button id="changeBtn">点我啊~~</button> <!-- IMPORT JS --> <script> let body = document.body; let changeBtn = document.getElementById('changeBtn'); // 从数组中拿到某一个样式值只需要:ary[数字索引] let i = 0; let ary = ['white', 'pink', 'lightblue', 'lightgreen', 'rgb(194,109,109)', 'orange', '#999']; // 点击按钮实现功能 changeBtn.onclick = function () { i++; // ary[i] 每一次点击基于累加后的 I 作为索引,从数组中拿到不同的颜色样式值 i > ary.length - 1 ? i = 0 : null; // 如果索引累加后比数组最大的索引都要大,我们让其从零开始即可 body.style.backgroundColor = ary[i]; } /* changeBtn.onclick = function () { // 获取当前的背景颜色 元素 .style.xxx 只能获取行内样式(颜色在样式中使用16进制方式,JS 中获取到的是 RGB 的值) let bg = body.style.backgroundColor; switch (bg) { case 'white': body.style.backgroundColor = 'red'; break; case 'red': body.style.backgroundColor = 'green'; break; case 'green': body.style.backgroundColor = 'blue'; break; default: body.style.backgroundColor = 'white'; } } */ </script></body></html>