看了妙味课堂js视频教程,课前预热第二节后,明白选项卡的实现原理,
就是:点击菜单所以的元素的className都为空,然后只给点击的当前元素添加className;
Tab选项卡和手风琴是一样的原理。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>手风琴</title> <style type="text/css"> * { margin:0; padding:0; } #menu { 280px; margin:50px auto; border:1px solid #ddd; border-bottom:none; font-size:13px; } #menu dt { background:#eee; padding:8px 10px; cursor:pointer; border-bottom:1px solid #ddd; color:#333; } #menu dt.active { background:#555; color:#fff; } #menu dd { padding:10px; height:100px; border-bottom:1px solid #ddd; display:none; color:#666; } #menu dd.current { display:block; } </style> </head> <body> <dl id="menu"> <dt class="active">菜单一</dt> <dd class="current">内容一</dd> <dt>菜单二</dt> <dd>内容二</dd> <dt>菜单三</dt> <dd>内容三</dd> <dt>菜单四</dt> <dd>内容四</dd> <dt>菜单五</dt> <dd>内容五</dd> </dl> <script type="text/javascript"> window.onload = function() { var menu = document.getElementById("menu"); var m_dt = menu.getElementsByTagName("dt"); var m_dd = menu.getElementsByTagName("dd"); for(var i=0; i<m_dt.length; i++) { m_dt[i].index = i; m_dt[i].onclick = function() { for(var i=0; i<m_dt.length; i++) { m_dt[i].className = ""; m_dd[i].className = ""; } this.className = "active"; m_dd[this.index].className = "current"; } } } </script> </body> </html>
<!doctype html> <html> <head> <meta charset="utf-8"> <title>选项卡</title> <style> * { margin:0; padding:0; } ul { list-style:none; 600px; border:1px solid #ddd; margin:0 auto; font-size:14px; } #menu { background:#eee; height:30px; margin-top:100px; box-shadow:1px 0 10px #eee; } #menu li { float:left; 120px; text-align:center; height:30px; line-height:30px; border-right:1px solid #ddd; cursor:pointer; } #menu li.active { background:#333; color:#fff; } #content { border-top:none; border-radius:0 0 4px 4px; box-shadow:1px 1px 15px #eee; } #content li { height:200px; display:none; padding:10px; } #content li.current { display:block; } </style> </head> <body> <ul id="menu"> <li class="active">菜单一</li> <li>菜单二</li> <li>菜单三</li> </ul> <ul id="content"> <li class="current">内容一</li> <li>内容二</li> <li>内容三</li> </ul> <script> window.onload = function() { var tab_t = document.getElementById("menu").getElementsByTagName("li"); var tab_c = document.getElementById("content").getElementsByTagName("li"); for(var i=0; i<tab_t.length; i++) { tab_t[i].index = i; tab_t[i].onclick = function() { for(var i=0; i<tab_t.length; i++) { tab_t[i].className = ""; tab_c[i].className = ""; } tab_c[this.index].className = "current"; this.className = "active"; } } } </script> </body> </html>