<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>选项卡简单</title> <style> /* css样式 */ button { width: 100px; height: 100px; } /* 按钮样式 */ #contens { width: 300px; height: 300px; } /* 内容外围样式 */ #contens div { width: 400px; height: 300px; line-height: 300px; text-align: center; } /* 内容外围中的div内容样式 */ </style> </head> <body> <button style="background-color: antiquewhite;" class="one">按钮1</button> <button style="background-color: #fff;" class="two">按钮2</button> <button style="background-color: #fff;" class="ther">按钮3</button> <button style="background-color: #fff;" class="four">按钮4</button> <div id="contens"> <div class="con" id="con1" style="display: block; background-color:antiquewhite;"> <p>内容1</p> </div> <div class="con" id="con2" style="display: none; background-color: cadetblue;"> <p>内容2</p> </div> <div class="con" id="con3" style="display: none; background-color: blue;"> <p>内容3</p> </div> <div class="con" id="con4" style="display: none; background-color: aquamarine;"> <p>内容4</p> </div> </div> </body> <script> let cons = document.getElementsByClassName('con'); // 获取所有class为con的元素,即内容div标签 console.log(cons); let buttons = document.getElementsByTagName('button'); // 获取所有button按钮标签 for (let i = 0; i < buttons.length; i++) { // 给每个按钮绑定点击事件 buttons[i].onclick = function() { console.log(i); // 打印当前按钮的下标 for (let j = 0; j < cons.length; j++) { buttons[j].style.backgroundColor = 'white'; // 将所有按钮的背景颜色设为白色 console.log(cons[j]); // 打印对应下标的内容div元素 cons[j].style.display = 'none'; // 将所有内容div元素隐藏 } buttons[i].style.backgroundColor = 'yellow'; // 将当前按钮的背景颜色设为黄色 cons[i].style.display = 'block'; // 将对应下标的内容div元素显示 } } </script> </html>
这个代码实现了一个简单的选项卡效果。页面上有四个按钮和四个内容区域,点击不同的按钮可以切换显示对应的内容区域。
代码分析如下:
- 使用
getElementsByTagName
方法获取页面上所有的button
元素,并将其保存在buttons
变量中。 - 遍历
buttons
数组,给每个按钮绑定点击事件。 - 点击事件的处理函数中,首先遍历
cons
数组,将所有按钮的背景颜色设为白色,并将所有内容div元素隐藏。 - 然后将当前点击的按钮的背景颜色设为黄色,并将对应的内容div元素显示出来。
这样就实现了一个简单的选项卡功能。