css样式
style> /*这里面是给div块元素添加css样式,css样式可以自己任意设置成自己想要的样式效果 */ body{ margin:0; padding:0; } div{ width:90%; height:260px; background:yellow; border:1px solid #ccc; display:none; /*这里把div块设置成不显示,如果不设置成隐藏话,页面显示时所有div块内容都显示在页面上,这不是我们想看到的*/ text-align:center; font-size:30px; line-height:200%; margin:5px; padding:10px; float:left; } .active{ background:blue; color:white; border-bottom:5px solid red; font-size:28px; } li{ list-style:none; width:30%; float:left; } </style>
js部分
window.onload=function(){ var aInput=document.getElementsByTagName("li");//获取所有的li标签元素 var aDiv=document.getElementsByTagName("div");//获取div元素 for(var i=0;i<aInput.length;i++){ //循环,给input加上点击事件,在点击时循环让所有选项卡的所有样式去掉,所有内容隐藏,然后让所点击的选项卡及对应内容显示。 aInput[i].index=i; aInput[i].onclick=function(){ for(var j=0;j<aInput.length;j++){//去掉所有input的class aInput[j].className="";//设置所有的className为空 aDiv[j].style.display="none";//设置所有的样式为不显示 } this.className="active";//设置当前className为active aDiv[this.index].style.display="block";//设置当前点击的相对的div的样式内容为显示 } } }
html部分
<body> <li class="active">选项卡一</li><!--设置页面初始打开时显示的选项卡 --> <li >选项卡二</li> <li >选项卡三</li> <div style="display:block">选项卡一内容</div><!--设置页面初始打开时显示的div块内容 --> <div>选项卡二内容</div> <div>选项卡三内容</div> </body>