//css.parent {width: 200px;height: 200px;position: relative;}.parent>div {width: 100%;height: 100%;position: absolute;}.html {background-color: pink;}.css {background-color: yellow;}.current {color: red;}//html<ul><li>html</li><li>css</li></ul><div class="parent"><div class="html">html</div><div class="css">css</div></div>//scriptvar lis = document.getElementsByTagName("li");var divs=document.querySelectorAll(".parent div");for(let i=0;i<lis.length;i++){lis[i].index=i;lis[i].onclick =function(){//1.遍历让所有的li移除current样式for(let i=0;i<lis.length;i++){lis[i].classList.remove("current");}//2.让当前元素添加current样式this.classList.add("current");console.log(this.index);//3.染发所有div隐藏for(let i=0;i<divs.length;i++){divs[i].style.display="none";}divs[this.index].style.display="block";}}
点击html与css进行文本样式以及div盒子的切换:
