批改状态:合格
老师批语:想过用自己的想法去改写吗? 如果是全抄的话, 不如就在本地完成了, 提交上来没必要了, 对不对
经典选项卡案例

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>作业: 经典选项卡案例</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}a {text-decoration: none;color: #555;}a:hover {text-decoration: underline;color: red;}li {list-style: none;}li:hover {cursor: default;}.tabs {width: 600px;height: 300px;margin: 30px;background-color: lightgreen;display: flex;flex-direction: column;}.tab {height: 36px;display: flex;}.tab li {flex: auto;text-align: center;line-height: 36px;background-color: #fff;}.tab li.active {background-color: lightgreen;}.tab li:hover {cursor: pointer;}/* 默认所有选项卡只有一个显示,其它隐藏 */.item {padding: 20px;display: none;}.item.active {display: block;}</style></head><body><div class="tabs"><!-- 导航 --><ul class="tab"><li class="active" data-index="1">水果</li><li data-index="2">手机</li><li data-index="3">汽车</li></ul><!-- 详情1 --><ul class="item active" data-index="1"><li><a href="">西瓜</a></li><li><a href="">苹果</a></li><li><a href="">香蕉</a></li></ul><!-- 详情2 --><ul class="item" data-index="2"><li><a href="">华为</a></li><li><a href="">小米</a></li><li><a href="">OPPO</a></li></ul><!-- 详情2 --><ul class="item" data-index="3"><li><a href="">吉利</a></li><li><a href="">奇瑞</a></li><li><a href="">长城</a></li></ul></div><script>// 使用事件代理const tab = document.querySelector(".tab");// 下面内容区列表const items = document.querySelectorAll(".item");// 给导航绑定点击事件tab.addEventListener("click", show, false);// tab.addEventListener("mouseover", show, false);// 事件回调function show(ev) {// 第一步:// 1. 清空导航之前的所有样式, 并将用户当前的选择项激活// 1.1 清空导航原有的样式Array.from(tab.children).forEach((item) =>item.classList.remove("active"));// 1.2 将用户当前的选择项激活ev.target.classList.toggle("active");// 第二步:// 2. 清空内容区已显示的内容,并根据导航对应的索引项(data-index)来确定将哪个内容区激活// 2.1 清空列表的原生的内容items.forEach((item) => item.classList.remove("active"));// 2.2 根据导航对应的索引项(data-index)来确定将哪个内容区激活items.forEach((item) =>item.dataset.index === ev.target.dataset.index? item.classList.toggle("active"): null);}</script></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号