任务描述:鼠标点击不同商品类别标题时切换不同页面
html代码:
<div class="tab"><div class="tab-head"><h3>家电</h3><ul><li><a class="active" href="javascript:;">热门</a></li><li><a href="javascript:;">电视影音</a></li><li><a href="javascript:;">电脑</a></li><li><a href="javascript:;">家居</a></li></ul></div><div class="tab-content"><div class="item active"><img src="./tab01.png" alt="" /></div><div class="item"><img src="./tab02.png" alt="" /></div><div class="item"><img src="./tab03.png" alt="" /></div><div class="item"><img src="./tab04.png" alt="" /></div></div></div>
css代码:
<style>*{margin: 0;padding: 0;}.tab{width: 600px;height: 350px;margin: 20px;border: 1px solid #e4e4e4;}.tab-head{width: 100%;height: 60px;line-height: 60px;display: flex;justify-content: space-between;}.tab-head h3{font-size: 25px;font-weight: normal;margin-left: 20px;}.tab-head ul{list-style: none;display: flex;justify-content: flex-end;}.tab-head ul li{margin: 0px 20px;font-size: 15px;}.tab-head ul li a{text-decoration: none;border-bottom: 2px solid transparent;color: #000000;}.tab-head ul li a.active{border-color: #ff7f00;color:#ff7f00;}.tab-content{padding: 0px 15px;}.tab-content .item{display: none;}.tab-content .item img{width: 100%;height: 100%;}.tab-content .item.active{display: block;}</style>
js代码:
<script>const title = document.querySelectorAll('.tab-head a')for(let i = 0; i < title.length; i++){title[i].addEventListener('mouseover',function(){document.querySelector('.tab-head .active').classList.remove('active')this.classList.add('active')document.querySelector('.tab-content .active').classList.remove('active')document.querySelector(`.tab-content .item:nth-child(${i + 1})`).classList.add('active')})}</script>
运行效果: