原生JavaScript( 五 )

20.选项卡<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><style>* {margin: 0;padding: 0;}.box {width: 600px;height: 400px;border: 1px solid red;margin: auto;}ul>li {list-style: none;float: left;width: 198px;height: 80px;background-color: gray;text-align: center;font-size: 30px;font-family: "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, monospace;line-height: 80px;border: 1px solid white;}/*添加外墙. 防止父级塌陷*/ul:after {display: table;content: "";clear: both;}.content {width: 600px;height: 320px;background-color: pink;display: none;text-align: center;line-height: 320px;font-size: 50px;}div.active {display: block;}li.active {background-color: red;}</style></head><body><div class="box"><ul><li class="active">首页</li><li>双色球</li><li>大乐透</li></ul><div class="content active">这里是首页</div><div class="content">这里是双色球</div><div class="content">这里是大乐透</div></div><script>var arr = document.getElementsByTagName('li')for (var i=0;i<arr.length;i++){// 绑定点击事件并添加样式arr[i].n = iarr[i].onclick = function(){// 删除所有的样式for (var j=0;j<arr.length;j++){arr[j].classList.remove('active')document.getElementsByClassName('content')[j].classList.remove('active')}this.classList.add('active')document.getElementsByClassName('content')[this.n].classList.add('active')}}</script></body></html>

推荐阅读