js实现选项卡功能
时间:2014-05-14 03:46:27
收藏:0
阅读:336
实现原理:
点击按钮时,改变选项卡中的class和改变div的style.display
1、选项卡的头部
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> input{ background:#fff;} .active{ background:red;} </style> </head> <body> <input type="button" value="1" class="active"/> <input type="button" value="2"/> <input type="button" value="3"/> </body> <script type="text/javascript"> var aBtn = document.getElementsByTagName("input"); var i = 0; for(i=0;i<aBtn.length;i++){ aBtn[i].onclick = function(){ //当点击某个按钮时,先将所有的按钮中的class清空(这里清空的事active) for(i=0;i<aBtn.length;i++){ aBtn[i].className = ‘‘; } this.className = ‘active‘;/*this代表被点击的那个按钮,被点击的那个按钮加上active这个class*/ }; } </script> </html>
2、完成这个效果的实现:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> input{ background:#fff;} .active{ background:red;} div{ width:200px; height:200px; background-color:#ccc; display:none;} </style> </head> <body> <input type="button" value="1" class="active"/> <input type="button" value="2"/> <input type="button" value="3"/> <div style="display:block;">111</div> <div>222</div> <div>333</div> </body> <script type="text/javascript"> var aBtn = document.getElementsByTagName("input"); var oDiv = document.getElementsByTagName("div"); var i = 0; for(i=0;i<aBtn.length;i++){ aBtn[i].index=i;//给所有的按钮加上索引值 aBtn[i].onclick = function(){ //当点击某个按钮时,先将所有的按钮中的class清空(这里清空的事active) for(i=0;i<aBtn.length;i++){ aBtn[i].className = ‘‘; oDiv[i].style.display=‘none‘; } //alert(this.index); oDiv[this.index].style.display="block"; this.className = ‘active‘;/*this代表被点击的那个按钮,被点击的那个按钮加上active这个class*/ }; } </script> </html>
评论(0)