使用JavaScript实现选项卡
使用JavaScript实现选项卡
点击选项卡时内容随之改变,实现点击选项卡切换
HTML部分:
<ul><li>1</li><li>2</li><li>3</li><li>4</li></ul><div class="current">1</div><div>2</div><div>3</div><div>4</div>
css部分:
<style>* {margin: 0;padding: 0;}ul {display: flex;justify-content: space-between;width: 800px;height: 100px;margin: 50px auto;}ul li {list-style: none;width: 200px;height: 100px;background-color: pink;text-align: center;line-height: 100px;/* float: left; */cursor: pointer;}div {width: 800px;height: 400px;background-color: skyblue;/* margin: 20px auto; */position: absolute;top: 200px;left: 50%;transform: translate(-50%);text-align: center;color: #fff;font-size: 100px;line-height: 400px;display: none;}.current {/* z-index: 33; */display: block;}</style>
JavaScript部分:
<script>var lis = document.querySelectorAll('li')var divs = document.querySelectorAll('div')console.dir(divs[0])// divs[1].zindex = 33// console.log(lis)// 第一层循环:给每一个li设置索引属性;给每一个li注册点击事件for (var i = 0; i < lis.length; i++) {lis[i].setAttribute('index', i)lis[i].onclick = function() {// 这个循环目的是排他思想 让所有的li背景色是空 当前的被点击的Li高亮显示for (var i = 0; i < lis.length; i++) {lis[i].style.backgroundColor = ''}// 当前的被点击的Li高亮显示this.style.backgroundColor = 'yellow'// console.log(this.getAttribute('index'))// 获取当前被点击的li的索引 让对应的div显示var index = parseInt(this.getAttribute('index'))// divs[index].style.display = 'block'for (var i = 0; i < divs.length; i++) {divs[i].style.display = 'none'}divs[index].style.display = 'block'}}</script>